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 ythe root of the resulting AVL tree in one line.
Sample Input 1:5 88 70 61 96 120Sample Output 1:
70Sample Input 2:
7 88 70 61 96 120 90 65Sample Output 2:
88
题目大意:
代码:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *lchild,*rchild;
};
struct node * RR(struct node *root)
{
struct node *tmp=root->rchild;
root->rchild=tmp->lchild;
tmp->lchild=root;
return tmp;
}
struct node * LL(struct node *root)
{
struct node *tmp=root->lchild;
root->lchild=tmp->rchild;
tmp->rchild=root;
return tmp;
}
struct node * RL(struct node *root)
{
root->rchild=LL(root->rchild);
return RR(root);
}
struct node * LR(struct node *root)
{
root->lchild=RR(root->lchild);
return LL(root);
}
int getbalancenum(struct node *root)
{
if(root==NULL)
return 0;
int left=getbalancenum(root->lchild);
int right=getbalancenum(root->rchild);
return left>right?left+1:right+1;
}
struct node * insert_AVL_tree(struct node *root,int k)
{
if(root==NULL)
{
root=(struct node *)malloc(sizeof(struct node));
root->data=k;
root->lchild=NULL;
root->rchild=NULL;
}
else if(k<root->data)
{
root->lchild=insert_AVL_tree(root->lchild,k);
if(getbalancenum(root->lchild)-getbalancenum(root->rchild)==2)
{
if(k<root->lchild->data)
{
root=LL(root);
}
else
{
root=LR(root);
}
}
}
else
{
root->rchild=insert_AVL_tree(root->rchild,k);
if(getbalancenum(root->rchild)-getbalancenum(root->lchild)==2)
{
if(k<root->rchild->data)
{
root=RL(root);
}
else
{
root=RR(root);
}
}
}
return root;
};
int main()
{
int i,j,n,m,k,t;
struct node *root=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&k);
root=insert_AVL_tree(root,k);
}
printf("%d\n",root->data);
return 0;
}