将给定的一系列数字插入初始为空的AVL树,请你输出最后生成的AVL树的根结点的值。
输入格式:
输入的第一行给出一个正整数N(≤20),随后一行给出N个不同的整数,其间以空格分隔。
输出格式:
在一行中输出顺序插入上述整数到一棵初始为空的AVL树后,该树的根结点的值。
输入样例1:
5
88 70 61 96 120
输出样例1:
70
输入样例2:
7
88 70 61 96 120 90 65
输出样例2:
88
参考代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct AVLNode *AVLTree;
struct AVLNode{
int data;
AVLTree left;
AVLTree right;
int height; //树高
};
/*函数声明*/
int max(int a,int b);
int getHeight(AVLTree T); //求树高
AVLTree llRotation(AVLTree A); //LL旋转
AVLTree rrRotation(AVLTree A); //RR旋转
AVLTree lrRotation(AVLTree A); //LR旋转
AVLTree rlRotation(AVLTree A); //RL旋转
AVLTree Insert(AVLTree T,int x);//将x插入AVL树中,并返回调整后的树
int main()
{
int n,x;
scanf("%d",&n);
AVLTree T=NULL;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
T=Insert(T,x);
}
printf("%d",T->data);
return 0;
}
int max(int a,int b)
{
return a>b?a:b;
}
int getHeight(AVLTree T)
{
int hl,hr,maxh;
if(T)
{
hl=getHeight(T->left);
hr=getHeight(T->right);
maxh=max(hl,hr);
return (maxh+1);
}
else
{
return 0;
}
}
AVLTree llRotation(AVLTree A)
{
AVLTree B=A->left;
A->left=B->right;
B->right=A;
A->height=max(getHeight(A->left),getHeight(A->right))+1;
B->height=max(getHeight(B->left),A->height)+1;
return B;
}
AVLTree rrRotation(AVLTree A)
{
AVLTree B=A->right;
A->right=B->left;
B->left=A;
A->height=max(getHeight(A->left),getHeight(A->right))+1;
B->height=max(A->left,getHeight(B->right))+1;
return B;
}
AVLTree lrRotation(AVLTree A)
{
A->left=rrRotation(A->left);
return llRotation(A);
}
AVLTree rlRotation(AVLTree A)
{
A->right=llRotation(A->right);
return rrRotation(A);
}
/*将X插入AVL树T中,并且返回调整后的AVL树*/
AVLTree Insert(AVLTree T,int x)
{
if(!T)//若插入空树,则新建包含一个结点的树
{
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->data=x;
T->height=0;
T->left=T->right=NULL;
}
else if(x<T->data)//插入T的左子树
{
T->left=Insert(T->left,x);//如果需要左旋
if(getHeight(T->left)-getHeight(T->right)==2)//如果需要左旋
{
if(x<T->left->data)
{
T=llRotation(T);//LL旋转
}
else
{
T=lrRotation(T);//LR旋转
}
}
}
else if(x>T->data)//插入T的右子树
{
T->right=Insert(T->right,x);
if(getHeight(T->left)-getHeight(T->right)==-2)//如果需要右旋
{
if(x>T->right->data)
{
T=rrRotation(T);//RR旋转
}
else
{
T=rlRotation(T);//RL旋转
}
}
}
T->height=max(getHeight(T->right),getHeight(T->right))+1;//更新树高
return T;
}
思路:
建立AVL树,返回该树根结点的值,具体实现细节看代码。如何建立AVL树是这题的重点,关于平衡二叉树的原理和平衡二叉树调整的实例可以看这位博主写的博客 。
参考资料:
[1]中国大学MOOC.数据结构(浙江大学).平衡二叉树课件
[2]月雲之霄: https://blog.csdn.net/isunbin/article/details/81707606