题目:
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.
输入格式
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.
输出格式
For each test case, print the root of the resulting AVL tree in one line.
输入样例
5
88 70 61 96 120
输出样例
70
算法
二叉搜索树插入操作的基础之上,实时检查当时结点的高度因子,当高度因子大于1时,进行AVL树的调整
代码实现
int main()
{
int N;
scanf("%d",&N);
int i;
int V;
AVLTree T=NULL;
for(i=0;i<N;i++){
scanf("%d",&V);
T=Insertion(T,V);
}
printf("%d",T->Data);
return 0;
}
AVL调整操作:
右单旋
AVLTree SingleRightRotation ( AVLTree A )
{
AVLTree B=A->Right;
A->Right=B->Left;
B->Left=A;
A->Height=TreeHeight(A);
B->Height=TreeHeight(B);
return B;
}
左单旋
AVLTree SingleLeftRotation ( AVLTree A )
{
AVLTree B=A->Left;
A->Left=B->Right;
B->Right=A;
A->Height=TreeHeight(A);
B->Height=TreeHeight(B);
return B;
}
左右双旋
AVLTree DoubleLeftRightRotation ( AVLTree A )
{
AVLTree B=A->Left;
A->Left=SingleRightRotation(B);
A=SingleLeftRotation(A);
A->Height=TreeHeight(A);
B->Height=TreeHeight(B);
return A;
}
左右双旋
AVLTree DoubleRightLeftRotation ( AVLTree A )
{
AVLTree B=A->Right;
A->Right=SingleLeftRotation(B);
A=SingleRightRotation(A);
A->Height=TreeHeight(A);
B->Height=TreeHeight(B);
return A;
}
存储方式
typedef struct AVLNode* AVLTree;
struct AVLNode{
int Data;
AVLTree Left;
AVLTree Right;
int Height;
};
AVLTree CreateNode(int V)
{
AVLTree T=(AVLTree)malloc(sizeof(struct AVLNode));
T->Data=V;
T->Left=NULL;
T->Right=NULL;
T->Height=0;
return T;
}
计算树高
int TreeHeight(AVLTree T)
{
if(T==NULL)return -1;
if(T->Left==NULL&&T->Right==NULL)return 0;
return MAX(TreeHeight(T->Left),TreeHeight(T->Right))+1;
}
计算结点的高度因子
int HeightFactor(AVLTree T)
{
int factor=-1;
if(T->Left==NULL&&T->Right==NULL){
factor=0;
}else if(T->Left==NULL&&T->Right!=NULL){
factor=-(T->Right->Height+1);
}else if(T->Left!=NULL&&T->Right==NULL){
factor=T->Left->Height+1;
}else if(T->Left!=NULL&&T->Right!=NULL){
factor=T->Left->Height-T->Right->Height;
}
return factor;
}
插入函数
AVLTree Insertion(AVLTree T,int V)
{
if(!T){
T=CreateNode(V);
}else{
if(V<T->Data){
//向左插入
T->Left=Insertion(T->Left,V);
if(HeightFactor(T)==2){
AVLTree A=T->Left;
if(V<A->Data){
T=SingleLeftRotation(T);
}else{
T=DoubleLeftRightRotation(T);
}
}
}else{
//向右插入
T->Right=Insertion(T->Right,V);
if(HeightFactor(T)<=-2){
AVLTree A=T->Right;
if(V<A->Data){
T=DoubleRightLeftRotation(T);
}else{
T=SingleRightRotation(T);
}
}
}
//没有AVL调整操作时,调整当前结点高度
//提示:结点需要进行AVL调整时,已经在函数内部更新结点高度
T->Height=TreeHeight(T);
}
return T;