DS二叉平衡树构建

Input

第一行输入测试数据组数t; 每组测试数据,第一行输入结点数n, 第二行输入n个结点值。

Output

对每组测试数据,按中序遍历的顺序输出树中,结点值及平衡因子(测试数据没有空树),即结点值:平衡因子,不同结点之间间隔一个空格。

Input
8
3
64 5 1
3
64 5 13
6
64 78 5 1 13 15
6
64 78 5 1 13 10
3
64 78 100
3
64 80 70
6
64 30 80 90 70 68
6
64 30 80 90 70 75
Output
1:0 5:0 64:0
5:0 13:0 64:0
1:0 5:1 13:0 15:0 64:0 78:0
1:0 5:0 10:0 13:0 64:-1 78:0
64:0 78:0 100:0
64:0 70:0 80:0
30:0 64:0 68:0 70:0 80:-1 90:0
30:0 64:1 70:0 75:0 80:0 90:0
#include 

struct TreeNode {
    int val;
    int height;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int x) : val(x), height(1), left(nullptr), right(nullptr) {}
};

int max(int a, int b) {
    return (a > b) ? a : b;
}

int getHeight(TreeNode* root) {
    if (!root) return 0;
    return root->height;
}

int getBalanceFactor(TreeNode* root) {
    if (!root) return 0;
    return getHeight(root->left) - getHeight(root->right);
}

TreeNode* rightRotate(TreeNode* y) {
    TreeNode* x = y->left;
    TreeNode* T2 = x->right;

    x->right = y;
    y->left = T2;

    y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
    x->height = max(getHeight(x->left), getHeight(x->right)) + 1;

    return x;
}

TreeNode* leftRotate(TreeNode* x) {
    TreeNode* y = x->right;
    TreeNode* T2 = y->left;

    y->left = x;
    x->right = T2;

    x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
    y->height = max(getHeight(y->left), getHeight(y->right)) + 1;

    return y;
}

TreeNode* insert(TreeNode* root, int val) {
    if (!root) return new TreeNode(val);

    if (val < root->val) {
        root->left = insert(root->left, val);
    }
    else if (val > root->val) {
        root->right = insert(root->right, val);
    }
    else {
        return root;
    }

    root->height = 1 + max(getHeight(root->left), getHeight(root->right));

    int balance = getBalanceFactor(root);

    if (balance > 1 && val < root->left->val) return rightRotate(root);
    if (balance < -1 && val > root->right->val) return leftRotate(root);
    if (balance > 1 && val > root->left->val) {
        root->left = leftRotate(root->left);
        return rightRotate(root);
    }
    if (balance < -1 && val < root->right->val) {
        root->right = rightRotate(root->right);
        return leftRotate(root);
    }

    return root;
}

void inorderTraversal(TreeNode* root) {
    if (!root) return;

    inorderTraversal(root->left);
    std::cout << root->val << ":" << getBalanceFactor(root) << " ";
    inorderTraversal(root->right);
}

int main() {
    int t;
    std::cin >> t;

    while (t--) {
        int n;
        std::cin >> n;

        TreeNode* root = nullptr;

        for (int i = 0; i < n; ++i) {
            int val;
            std::cin >> val;
            root = insert(root, val);
        }

        inorderTraversal(root);
        std::cout << std::endl;
    }

    return 0;
}

你可能感兴趣的:(数据结构)