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.
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
平衡二叉树:http://lib.csdn.net/article/datastructure/9204
https://www.liuchuo.net/archives/2178
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node *left,*right;
};
typedef struct Node* AVL;
AVL RightRot(AVL t)
{
AVL p=t->left;
t->left=p->right;
p->right=t;
return p;
}
AVL LeftRot(AVL t)
{
AVL p=t->right;
t->right=p->left;
p->left=t;
return p;
}
AVL LeftRightRot(AVL t)
{
t->left=LeftRot(t->left);
return RightRot(t);
}
AVL RightLeftRot(AVL t)
{
t->right=RightRot(t->right);
return LeftRot(t);
}
int GetHeight(AVL t)
{
if(t==NULL) return 0;
return max(GetHeight(t->left),GetHeight(t->right))+1;
}
AVL it(AVL t,int x)
{
if(t==NULL)
{
t=new Node();
t->data=x;
t->left=t->right=NULL;
}
else if(x<t->data)
{
t->left=it(t->left,x);
if(GetHeight(t->left)-GetHeight(t->right)==2)
{
if(x<t->left->data) t=RightRot(t); //
else t=LeftRightRot(t);
}
}
else
{
t->right=it(t->right,x);
if(GetHeight(t->left)-GetHeight(t->right)==-2)
{
if(x>t->right->data) t=LeftRot(t); //
else t=RightLeftRot(t);
}
}
return t;
}
int main(void)
{
int n,i,tp;
AVL r=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&tp);
r=it(r,tp);
}
printf("%d\n",r->data);
return 0;
}