PAT甲级——A1066 Root of AVL Tree

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

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.

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 (≤) which is the total number of keys to be inserted. Then 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```

`70`

Sample Input 2:

```7
88 70 61 96 120 90 65```

Sample Output 2:

`88`
``` 1 #include <iostream>
2 using namespace std;
3 struct node {
4     int val;
5     struct node *left, *right;
6 };
7 node *rotateLeft(node *root) {
8     node *t = root->right;
9     root->right = t->left;
10     t->left = root;
11     return t;
12 }
13 node *rotateRight(node *root) {
14     node *t = root->left;
15     root->left = t->right;
16     t->right = root;
17     return t;
18 }
19 node *rotateLeftRight(node *root) {
20     root->left = rotateLeft(root->left);
21     return rotateRight(root);
22 }
23 node *rotateRightLeft(node *root) {
24     root->right = rotateRight(root->right);
25     return rotateLeft(root);
26 }
27 int getHeight(node *root) {
28     if(root == NULL) return 0;
29     return max(getHeight(root->left), getHeight(root->right)) + 1;
30 }
31 node *insert(node *root, int val) {
32     if(root == NULL) {
33         root = new node();
34         root->val = val;
35         root->left = root->right = NULL;
36     } else if(val < root->val) {
37         root->left = insert(root->left, val);
38         if(getHeight(root->left) - getHeight(root->right) == 2)
39             root = val < root->left->val ? rotateRight(root) : rotateLeftRight(root);
40     } else {
41         root->right = insert(root->right, val);
42         if(getHeight(root->left) - getHeight(root->right) == -2)
43             root = val > root->right->val ? rotateLeft(root) : rotateRightLeft(root);
44     }
45     return root;
46 }
47 int main() {
48     int n, val;
49     scanf("%d", &n);
50     node *root = NULL;
51     for(int i = 0; i < n; i++) {
52         scanf("%d", &val);
53         root = insert(root, val);
54     }
55     printf("%d", root->val);
56     return 0;
57 }```