Root of AVL Tree

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.

 

 

 

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 65

Sample Output 2:

88 

 

 

 1 #include<iostream>
 2 using namespace std;
 3 struct treenode{
 4        int data,h;
 5        treenode* left=NULL;
 6        treenode* right=NULL;
 7 };
 8 using tree=treenode*;
 9 int height(tree t){
10     //cout<<"height(tree t)"<<endl;
11     if(!t) return 0;
12     return max(height(t->left),height(t->right))+1;
13 }
14 tree RotateLL(tree t){
15     //cout<<" RotateLL(tree t)"<<endl;
16     tree a=t->left;
17     t->left=a->right;
18     a->right=t;
19     a->h=max(height(a->left),height(a->right))+1;
20     t->h=max(height(t->left),height(t->right))+1;
21     return a; 
22 }
23 tree RotateRR(tree t){
24    //cout<<"RotateRR(tree t)"<<endl;
25     tree a=t->right;
26     t->right=a->left;
27     a->left=t;
28     a->h=max(height(a->left),height(a->right))+1;
29     t->h=max(height(t->left),height(t->right))+1;
30     return a; 
31 }
32 tree RotateLR(tree t){
33 //cout<<"RotateLR(tree t)"<<endl;
34     t->left=RotateRR(t->left);
35     return RotateLL(t);
36 }
37 tree RotateRL(tree t){
38    //cout<<"RotateRL(tree t)"<<endl;
39     t->right=RotateLL(t->right);
40     return RotateRR(t);
41 }
42 tree insert(tree t,int v){
43 //cout<<" insert(tree t,int v)"<<endl;
44     if(t==NULL){
45        t=new treenode();
46        t->data=v; t->h=0;
47        return t;
48     }else if(v<t->data){
49        t->left=insert(t->left,v);
50        if(height(t->left)-height(t->right)==2)
51        if(v<t->left->data) 
52        t=RotateLL(t);
53        else t=RotateLR(t); 
54     }else{
55        t->right=insert(t->right,v);
56        if(height(t->left)-height(t->right)==-2)
57        if(v>t->right->data)
58        t=RotateRR(t);
59        else t=RotateRL(t); 
60 }
61     t->h=height(t);
62     return t;
63 } 
64 int main(){
65     int n;
66     cin>>n;
67     tree t=NULL;
68     for(int i=0;i<n;i++){
69         int v; cin>>v;
70         t=insert(t,v);
71     }
72     cout<<t->data<<endl;
73     return 0;
74 }

 

 

 

 

 

posted @ 2017-12-18 09:11  A-Little-Nut  阅读(131)  评论(0编辑  收藏  举报