将给定的一系列数字插入初始为空的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 int ElementType;
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
ElementType data;
AVLTree left;
AVLTree right;
int h;//树高
};
int max(int a,int b)
{
return a>b?a:b;
}
int getH(AVLTree t);
AVLTree ll(AVLTree a);
AVLTree rr(AVLTree a);
AVLTree lr(AVLTree a);
AVLTree rl(AVLTree a);
AVLTree insert(AVLTree t,ElementType x);
int main(){
int n,k,i;
AVLTree t=NULL;//初始为空的AVL树
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&k);
t=insert(t,k);//逐一插入
}
printf("%d\n",t->data);
return 0;
}
int getH(AVLTree t){
if(t) return t->h;
else return -1;
}
AVLTree ll(AVLTree a){
//a必须有一个左子节点b
AVLTree b=a->left;
a->left=b->right;
b->right=a;
a->h=max(getH(a->left),getH(a->right))+1;
b->h=max(getH(b->left),a->h)+1;
return b;
}
AVLTree rr(AVLTree a){
//a必须有一个右子节点
AVLTree b=a->right;
a->right=b->left;
b->left=a;
a->h=max(getH(a->left),getH(a->right))+1;
b->h=max(getH(b->right),a->h)+1;
return b;
}
AVLTree lr(AVLTree a){//lr左右双旋
AVLTree b,c;
b=a->left;
c=b->right;
b->right=c->left;
a->left=c->right;
c->left=b;
c->right=a;
b->h=max(getH(b->left),getH(b->right))+1;
a->h=max(getH(a->left),getH(a->right))+1;
c->h=max(b->h,a->h)+1;
return c;
}
AVLTree rl(AVLTree a){//rl右左双旋
AVLTree b,c;
b=a->right;
c=b->left;
b->left=c->right;
a->right=c->left;
c->right=b;
c->left=a;
b->h=max(getH(b->left),getH(b->right))+1;
a->h=max(getH(a->left),getH(a->right))+1;
c->h=max(b->h,a->h)+1;
return c;
}
AVLTree insert(AVLTree t,ElementType x){
if(!t){//插入空树
t=(AVLTree)malloc(sizeof(struct AVLNode));
t->data=x;
t->h=0;
t->left=t->right=NULL;
}else if(x<t->data){
//插入T的左子树
t->left=insert(t->left,x) ;
//如果需要左旋
if(getH(t->left)-getH(t->right)==2)
if(x<t->left->data)
t=ll(t);//左单旋
else
t=lr(t);//左右双旋
} else if(x>t->data){
t->right=insert(t->right,x);
//如果需要右旋
if(getH(t->left)-getH(t->right)==-2)
if(x>t->right->data)
t=rr(t);//右单旋
else
t=rl(t);//右左双旋
}
//更新树高
t->h=max(getH(t->left),getH(t->right))+1;
return t;
}