解题代码
#include<stdio.h>
#include<stdlib.h>
typedef struct TNode* AVLTree;
struct TNode {
int data;
AVLTree Left, Right;
int height;
};
AVLTree Insert(AVLTree T, int K);
int Max(int A, int B);
int Getheight(AVLTree p);
AVLTree Singleleftrotate(AVLTree A);
AVLTree Singlerightrotate(AVLTree A);
AVLTree Doubleleftrightrotate(AVLTree A);
AVLTree Doublerightleftrotate(AVLTree A);
int main()
{
int N, K, i;
AVLTree T = NULL;
scanf("%d", &N);
for (i = 0; i < N; i++) {
scanf("%d", &K);
T = Insert(T, K);
}
printf("%d", T->data);
return 0;
}
AVLTree Insert(AVLTree T, int K) {
if (!T) {
T = malloc(sizeof(struct TNode));
T->data = K;
T->Left = T->Right = NULL;
}
else if (K < T->data) {
T->Left = Insert(T->Left, K);
if (Getheight(T->Left) - Getheight(T->Right) == 2) {
if (K < T->Left->data) T=Singleleftrotate(T);
else if (K > T->Left->data) T=Doubleleftrightrotate(T);
}
}
else if (K > T->data) {
T->Right = Insert(T->Right, K);
if (Getheight(T->Right) - Getheight(T->Left) == 2) {
if (K > T->Right->data) T=Singlerightrotate(T);
else if (K < T->Right->data) T=Doublerightleftrotate(T);
}
}
T->height = Max(Getheight(T->Left), Getheight(T->Right)) + 1;
return T;
}
int Max(int A, int B) {
return A > B ? A : B;
}
int Getheight(AVLTree p) {
if (!p) return -1;
else return p->height;
}
AVLTree Singleleftrotate(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 Singlerightrotate(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 Doubleleftrightrotate(AVLTree A) {
AVLTree B = A->Left;
A->Left = Singlerightrotate(B);
return Singleleftrotate(A);
}
AVLTree Doublerightleftrotate(AVLTree A) {
AVLTree B = A->Right;
A->Right = Singleleftrotate(B);
return Singlerightrotate(A);
}
测试结果
问题整理
1.注意Insert函数的结构。