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 (<=20) 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 688
1 #include<iostream> 2 #include<vector>
3 #include<algorithm> 4 #include<queue> 5 #include<stack> 6 using namespace std; 7 8 class Node{ 9 public: 10 int value; 11 bool vis; 12 Node *left, *right; 13 Node(){left = NULL; right = NULL; vis = true;} 14 }; 15 24 25 Node* roateLeft(Node* root) { 26 Node* t = root->right; 27 root->right = t->left; 28 t->left = root; 29 return t; 30 } 31 32 Node* roateRight(Node* root){ 33 Node* t = root->left; 34 root->left = t->right; 35 t->right = root; 36 return t; 37 } 38 39 Node* roateRightLeft(Node* root){ 40 root->right = roateRight(root->right); 41 return roateLeft(root); 42 } 43 44 Node* roateLeftRight(Node* root){ 45 root->left = roateLeft(root->left); 46 return roateRight(root); 47 } 48 49 int getHeight(Node* root){ 50 if(root == NULL) return 0; 51 int l = getHeight(root->left) + 1; 52 int r = getHeight(root->right) + 1; 53 return l>r ? l : r; 54 } 55 56 Node* build(Node* root, int value){ 57 if(root == NULL) { 58 root = new Node(); 59 root->value = value; 60 } else if(root->value > value){ 61 root->left = build(root->left, value); 62 if(getHeight(root->left) - getHeight(root->right) == 2) { 63 if(value < root->left->value) root = roateRight(root); 64 else root = roateLeftRight(root); 65 } 66 }else{ 67 root->right = build(root->right, value); 68 if(getHeight(root->right) - getHeight(root->left) == 2) { 69 if(value < root->right->value) root = roateRightLeft(root); 70 else root = roateLeft(root); 71 } 72 } 73 return root; 74 }
199 int main(){ 200 Node* root = NULL;
int n, i;
cin>>n;
for(i = 0; i < n; i++){
int temp;
cin>>temp;
root = build(root, temp);
}
cout<<root->val; 207 return 0;}