04-树5 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.
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:
588 70 61 96 120
Sample Output 1:
70
Sample Input 2:
788 70 61 96 120 90 65
Sample Output 2:
88
#include#include using namespace std;struct AVL{ int data; int height; struct AVL *left; struct AVL *right;};int getHeight(AVL *T){ if(T) return max(getHeight(T->left),getHeight(T->right))+1; else return 0;}AVL *LL(AVL *A){ AVL *B=new AVL; B=A->left; A->left=B->right; B->right=A; A->height=max(getHeight(A->left),getHeight(A->right))+1; B->height=max(getHeight(B->left),A->height)+1; return B;}AVL *RR(AVL *A){ AVL *B=new AVL; B=A->right; A->right=B->left; B->left=A; A->height=max(getHeight(A->left),getHeight(A->right))+1; B->height=max(A->height,getHeight(B->right))+1; return B;}AVL *LR(AVL *A){ A->left=RR(A->left); return LL(A);}AVL *RL(AVL *A){ A->right=LL(A->right); return RR(A);}AVL* Insert(int x,AVL *T){ if(!T){ T=new AVL; T->data=x; T->height=0; T->left=T->right=NULL; } else if(x data){ T->left=Insert(x,T->left); if(getHeight(T->left)-getHeight(T->right)==2){ if(x left->data) T=LL(T); else T=LR(T); } } else if(x>T->data){ T->right=Insert(x,T->right); if(getHeight(T->left)-getHeight(T->right)==-2){ if(x>T->right->data) T=RR(T); else T=RL(T); } } T->height=max(getHeight(T->left),getHeight(T->right))+1; return T;}void deleteTree(AVL *T){ if(T->left) deleteTree(T->left); if(T->right) deleteTree(T->right); delete T;}int main() { int n,num; AVL *T=NULL; cin>>n; for(int i=0;i >num; T=Insert(num,T); } cout< data<