// AVL树的建立
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode* AVLTree;
typedef int ElementType;
struct AVLNode {
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
int Max(int a, int b) {
return a > b ? a : b;
}
int GetHeight(AVLTree T) {
if(!T) return -1;
else return T->Height;
}
//这里使用getheight为了防止height为初始化的情况
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(A->Height, GetHeight(B->Right)) + 1;
return B;
}
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 DoubleLeftRightRotation(AVLTree A) {
A->Left = SingleRightRotation(A->Left);
//将B与C做右单旋,返回C;
return SingleLeftRotation(A);
//将A与C做左单旋,返回C;
}
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->Height = 0;
T->Left = T->Right = NULL;
}
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);
}
}
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);
}
}
T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1;
return T;
}
int main() {
AVLTree T = NULL;
//方便直接insert;
int n, x;
scanf("%d", &n);
while(n--) {
scanf("%d", &x);
T = Insert(T, x);
}
if(T) printf("%d\n", T->Data);
return 0;
}
04-树5 Root of AVL Tree (25分)
最新推荐文章于 2023-05-11 10:54:11 发布