PAT (Advanced Level) Practice 1066 Root of AVL Tree (25 min) balanced binary tree [AVL]

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
Here Insert Picture Description
Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N ( 20 ) N (≤20) which is the total number of keys to be inserted. Then N N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88

The meaning of problems

Gives some of the nodes, is inserted into the AVL tree, the root of the final tree seeking.

Thinking

Achieve insertion AVL tree.

Code

#include <algorithm>
#include <cstdio>

using namespace std;

struct node {
    int v;
    node *left, *right;

    static int getHeight(node *root) {
        return root ? max(getHeight(root->left), getHeight(root->right)) + 1 : 0;
    }

    int getBalanceFactor() {
        return getHeight(left) - getHeight(right);
    }
};

void leftRotate(node *&root) {
    node *temp = root->right;
    root->right = temp->left;
    temp->left = root;
    root = temp;
}

void rightRotate(node *&root) {
    node *temp = root->left;
    root->left = temp->right;
    temp->right = root;
    root = temp;
}

void insert(node *&root, int v) {
    if (root == nullptr) {
        root = new node{v};
        return;
    }

    if (v < root->v) {
        insert(root->left, v);
        if (root->getBalanceFactor() == 2) {
            if (v < root->left->v) {
                rightRotate(root);
            } else {
                leftRotate(root->left);
                rightRotate(root);
            }
        }
    } else {
        insert(root->right, v);
        if (root->getBalanceFactor() == -2) {
            if (v >= root->right->v) {
                leftRotate(root);
            } else {
                rightRotate(root->right);
                leftRotate(root);
            }
        }
    }
}

int main() {
    node *root = nullptr;

    int n, v;
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", &v);
        insert(root, v);
    }
    printf("%d\n", root->v);
}
Published 184 original articles · won praise 19 · views 20000 +

Guess you like

Origin blog.csdn.net/Exupery_/article/details/104206350