1066 Root of AVL Tree (25分)
输入样例1
5
88 70 61 96 120输出样例1
70
输入样例2
7
88 70 61 96 120 90 65输出样例2
88
运行截图
代码
#include <iostream>
using namespace std;
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
int data;
AVLTree Left,Right;
int Height;
};
int GetHeight(AVLTree A){
int Height=0;
if (A){
Height=max(GetHeight(A->Left),GetHeight(A->Right));
}
return ++Height;
}
AVLTree SingleLeftRotation(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 SingleRightRotation(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(GetHeight(B->Right),A->Height)+1;
return B;
}
AVLTree DoubleLeftRightRotation ( AVLTree A )
{
A->Left = SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}
AVLTree DoubleRightLeftRotation ( AVLTree A )
{
A->Right = SingleLeftRotation(A->Right);
return SingleRightRotation(A);
}
AVLTree Insert(AVLTree T,int x){
if(!T){
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->data=x;
T->Left= nullptr;
T->Right= nullptr;
T->Height=0;
} else if (x<T->data){
T->Left=Insert(T->Left,x);
if (GetHeight(T->Left)-GetHeight(T->Right)==2){
if (x<T->Left->data)
T=SingleLeftRotation(T);
else
T=DoubleLeftRightRotation(T);
}
} else if (x>T->data){
T->Right=Insert(T->Right,x);
if (GetHeight(T->Right)-GetHeight(T->Left)==2){
if (x>T->Right->data)
T=SingleRightRotation(T);
else
T=DoubleRightLeftRotation(T);
}
}
T->Height=max(GetHeight(T->Left),GetHeight(T->Right))+1;
return T;
}
int main()
{
int n;
cin>>n;
int x;
AVLTree A;
while (n--){
cin>>x;
A=Insert(A,x);
}
cout<<A->data;
return 0;
}