1066. Root of AVL Tree (25)
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.
![](http://nos.patest.cn/79_mtxjq1kj3gx.jpg)
![](http://nos.patest.cn/79_mtxjqnwja2o.jpg)
![](http://nos.patest.cn/79_mtxjr4gyzdg.jpg)
![](http://nos.patest.cn/79_mtxjrh51o9y.jpg)
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 ythe 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
解题思路:建立AVL树。参考链接来建立AVL树。http://www.cppblog.com/cxiaojia/archive/2013/07/22/187776.html
#include<iostream> #include<cstdio> #include<vector> #include<cmath> using namespace std; struct Tree{ int val; int hight; Tree* left; Tree* right; Tree():hight(0),left(NULL),right(NULL){} }; int getHeight(Tree* node){ if(node!=NULL){ return node->hight; } return -1; } int max(int a,int b){ return a>b?a:b; } Tree* SingleRotateLeft(Tree* k2){ Tree* k1; k1=k2->left; k2->left=k1->right; k1->right=k2; k2->hight=max(getHeight(k2->right),getHeight(k2->left))+1; k1->hight=max(getHeight(k1->right),getHeight(k1->left))+1; return k1; } Tree* SingleRotateRight(Tree* k2){ Tree* k1; k1=k2->right; k2->right=k1->left; k1->left=k2; k2->hight=max(getHeight(k2->right),getHeight(k2->left))+1; k1->hight=max(getHeight(k1->right),getHeight(k1->left))+1; return k1; } Tree* DoubleRotateLR(Tree* k2){ k2->left=SingleRotateRight(k2->left); return SingleRotateLeft(k2); } Tree* DoubleRotateRL(Tree* k2){ k2->right=SingleRotateLeft(k2->right); return SingleRotateRight(k2); } bool isBalanced(Tree* left,Tree* right){ return abs(getHeight(left)-getHeight(right))<2; } Tree* Insert(Tree* tree,int data){ if(tree==NULL){ tree=new Tree(); tree->val=data; return tree; } if(tree->val>=data){ tree->left=Insert(tree->left,data); if(!isBalanced(tree->left,tree->right)){ if(data < tree->left->val){ tree=SingleRotateLeft(tree); }else { tree=DoubleRotateLR(tree); } } }else { tree->right=Insert(tree->right,data); if(!isBalanced(tree->left,tree->right)){ if(data > tree->right->val){ tree=SingleRotateRight(tree); }else { tree=DoubleRotateRL(tree); } } } tree->hight=max(getHeight(tree->left),getHeight(tree->right))+1; return tree; } int main(){ int n; Tree* tree=NULL; scanf("%d",&n); while(n--){ int data; scanf("%d",&data); tree=Insert(tree,data); } printf("%d\n",tree->val); return 0; }