Source:
Description:
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
Sample Output 1:
70
Sample Input 2:
7 88 70 61 96 120 90 65
Sample Output 2:
88
Keys:
Code:
1 /* 2 Data: 2019-06-24 15:44:17 3 Problem: PAT_A1066#Root of AVL Tree 4 AC: 12:20 5 6 题目大意: 7 构造AVL树,打印根结点 8 */ 9 #include<cstdio> 10 #include<algorithm> 11 using namespace std; 12 struct node 13 { 14 int data,height; 15 node *lchild,*rchild; 16 }; 17 18 int GetHeight(node *root) 19 { 20 if(root == NULL) 21 return 0; 22 else 23 return root->height; 24 } 25 26 void UpdataHeight(node *&root) 27 { 28 root->height = max(GetHeight(root->lchild),GetHeight(root->rchild))+1; 29 } 30 31 int GetBalanceFactor(node *root) 32 { 33 return GetHeight(root->lchild) - GetHeight(root->rchild); 34 } 35 36 void LeftRotation(node *&root) 37 { 38 node *temp = root->rchild; 39 root->rchild = temp->lchild; 40 temp->lchild = root; 41 UpdataHeight(root); 42 UpdataHeight(temp); 43 root = temp; 44 } 45 46 void RightRotation(node *&root) 47 { 48 node *temp = root->lchild; 49 root->lchild = temp->rchild; 50 temp->rchild = root; 51 UpdataHeight(root); 52 UpdataHeight(temp); 53 root = temp; 54 } 55 56 void Insert(node *&root, int x) 57 { 58 if(root == NULL) 59 { 60 root = new node; 61 root->data = x; 62 root->height=1; 63 root->lchild = root->rchild = NULL; 64 } 65 else if(x < root->data) 66 { 67 Insert(root->lchild, x); 68 UpdataHeight(root); 69 if(GetBalanceFactor(root) == 2) 70 { 71 if(GetBalanceFactor(root->lchild) == 1) 72 RightRotation(root); 73 else 74 { 75 LeftRotation(root->lchild); 76 RightRotation(root); 77 } 78 } 79 } 80 else 81 { 82 Insert(root->rchild, x); 83 UpdataHeight(root); 84 if(GetBalanceFactor(root) == -2) 85 { 86 if(GetBalanceFactor(root->rchild) == -1) 87 LeftRotation(root); 88 else 89 { 90 RightRotation(root->rchild); 91 LeftRotation(root); 92 } 93 } 94 } 95 } 96 97 int main() 98 { 99 #ifdef ONLINE_JUDGE 100 #else 101 freopen("Test.txt", "r", stdin); 102 #endif // ONLINE_JUDGE 103 104 int n,x; 105 scanf("%d", &n); 106 node *root = NULL; 107 for(int i=0; i<n; i++) 108 { 109 scanf("%d", &x); 110 Insert(root, x); 111 } 112 printf("%d", root->data); 113 114 return 0; 115 }