#include <stdio.h>
#include <malloc.h>
struct AVLTNode
{
struct AVLTNode *lchild,*rchild;
int key;
int height;
}*T;
int Max(int a,int b)
{
int k=(a>b?a:b);
return k;
}
int ComputeHeight(struct AVLTNode*T)
{
if(T)
return T->height;
return 0;
}
struct AVLTNode*leftRotation(struct AVLTNode *root)
{
struct AVLTNode *p=root->rchild;
root->rchild=p->lchild;
p->lchild=root;
p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
return p;
}
struct AVLTNode*rightRotation(struct AVLTNode *root)
{
struct AVLTNode *p=root->lchild;
root->lchild=p->rchild;
p->rchild=root;
p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
return p;
}
struct AVLTNode*rightleftRotation(struct AVLTNode *root)
{
root->rchild=rightRotation(root->rchild);
return leftRotation(root);
}
struct AVLTNode*leftrightRotation(struct AVLTNode *root)
{
root->lchild=leftRotation(root->lchild);
return rightRotation(root);
}
void Insertion(int curkey,struct AVLTNode **T)
{
if((*T)==NULL)
{
(*T)=(struct AVLTNode*)malloc(sizeof(struct AVLTNode));
(*T)->lchild=(*T)->rchild=NULL;
(*T)->key=curkey;
(*T)->height=0;
}
else if(curkey<((*T)->key))
{
Insertion(curkey,&(*T)->lchild);
if(ComputeHeight((*T)->lchild)-ComputeHeight((*T)->rchild)==2)
{
curkey<(*T)->lchild->key?((*T)=rightRotation(*T)):((*T)=leftrightRotation(*T));
}
}
else if(curkey>(*T)->key)
{
Insertion(curkey,&(*T)->rchild);
if(ComputeHeight((*T)->rchild)-ComputeHeight((*T)->lchild)==2)
{
curkey>(*T)->rchild->key?((*T)=leftRotation(*T)):((*T)=rightleftRotation(*T));
}
}
(*T)->height=Max(ComputeHeight((*T)->lchild),ComputeHeight((*T)->rchild))+1;
}
int main()
{
int n,i;
T=NULL;
scanf("%d",&n);
for(i=0;i<n;++i)
{
int curkey;
scanf("%d",&curkey);
Insertion(curkey,&T);
}
printf("%d",T->key);
return 0;
}
转载于:https://www.cnblogs.com/xLester/p/7570383.html