![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/39cb3537bb91c1ae6b494573aeb40267.png)
#include <stdio.h>
#include <stdlib.h>
#define ElementType int
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode {
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
int Max ( int a, int b );
AVLTree SingleLeftRotation ( AVLTree A );
AVLTree SingleRightRotation ( AVLTree A );
AVLTree DoubleLeftRightRotation ( AVLTree A );
AVLTree DoubleRightLeftRotation ( AVLTree A );
AVLTree Insert( AVLTree T, ElementType X );
int GetHeight(AVLTree T);
int main() {
int N;
ElementType data;
scanf("%d",&N);
scanf("%d",&data);
N--;
AVLTree T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Data = data;
T->Height = 0;
T->Left = T->Right = NULL;
while(N--) {
scanf("%d",&data);
T=Insert(T,data);
}
printf("%d\n", T->Data);
return 0;
}
int Max ( int a, int b ) {
return a > b ? a : b;
}
int GetHeight(AVLTree T) {
if(T)
return T->Height;
else
return 0;
}
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->Right), GetHeight(A->Left) ) + 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, ElementType 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->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->Left)-GetHeight(T->Right) == -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;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c1fad696f69161ff85d3a1fbc68f8572.png)