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.
#include <bits/stdc++.h>
using namespace std;
int n;
struct node{
int x,h,p;
node *l,*r;
};
int update(node *t){
if(t == NULL)return 0;
t->h = max(update(t->l ),update(t->r )) + 1;
return t->h ;
}
node* insert(node *t,int a){
if(t == NULL){
t = new node;
t->x = a;
t->l = t->r = NULL;
t->h = 1;
t->p = 0;
return t;
}else {
if(a < t->x ){
t->l = insert(t->l ,a);
t->h = update(t);
t->p = update(t->l ) - update(t->r ) ;//计算平衡因子
if(t->p == 2){
if(t->l->p == 1){ //LL旋转
node *br,*b;
b = t->l ;
br = b->r ;
t->l = br;
b->r = t;
update(b);
return b;
}else if(t->l->p == -1){//LR旋转
node *b,*c,*cl,*cr;
b = t->l ;
c = b->r ;
cl = c->l ;
cr = c->r ;
b->r = cl;
t->l = cr;
c->l = b;
c->r = t;
update(c);
return c;
}
}
return t;
}else if(a > t->x ){
t->r = insert(t->r ,a);
t->h = update(t);
t->p = update(t->l ) - update(t->r ) ;
if(t->p == -2){
if(t->r->p == -1){ //RR旋转
node *b,*bl;
b = t->r ;
bl = b->l ;
t->r = bl;
b->l = t;
update(b);
return b;
}else if(t->r->p == 1){ //RL旋转
node *b,*c,*cl,*cr;
b = t->r ;
c= b->l ;
cl = c->l ;
cr = c->r ;
t->r = cl;
b->l = cr;
c->l = t;
c->r = b;
update(c);
return c;
}
}
return t;
}
}
}
int main()
{
cin>>n;
node *t = NULL;
for(int i = 1;i<=n;i++){
int a;
cin>>a;
t = insert(t,a);
}
cout<<t->x ;
return 0;
}