#include<stdio.h>
#include<stdlib.h>
struct AVLNode{
int Data;
int Height;
struct AVLNode * Left;
struct AVLNode * Right;
};
int Max(int a,int b){
return a>b?a:b;
}
int GetHeight(struct AVLNode*T){
if(T==NULL){
return 0;
}
else{
return 1+Max(GetHeight(T->Left),GetHeight(T->Right));
}
}
struct AVLNode* SLR(struct AVLNode * K2) {
struct AVLNode *K1;
K1 = K2->Left;
K2->Left = K1->Right;
K1->Right = K2;
// 旋转完后更新K1、K2的高度
K2->Height = Max(GetHeight(K2->Left), GetHeight(K2->Right)) + 1;
K1->Height = Max(GetHeight(K1->Left), K2->Height) + 1;
return K1;
}
struct AVLNode * SRR(struct AVLNode *K1) {
struct AVLNode *K2;
K2 = K1->Right;
K1->Right = K2->Left;
K2->Left = K1;
// 旋转完后更新K1、K2的深度
K1->Height = Max(GetHeight(K1->Left), GetHeight(K1->Right)) + 1;
K2->Height = Max(K1->Height, GetHeight(K2->Right)) + 1;
return K2;
}
struct AVLNode * DLR(struct AVLNode * K2)
{
K2->Left = SRR(K2->Left);
return SLR(K2);
}
struct AVLNode * DRR(struct AVLNode * K1)
{
K1->Right = SLR(K1->Right);
return SRR(K1);
}
struct AVLNode * InsertAVL(struct AVLNode * T, int X) {
if (T == NULL) {
T = (struct AVLNode*)malloc(sizeof(struct AVLNode));
T->Data = X;
T->Height = 1;
T->Left = T->Right = NULL;
} else if (X < T->Data) {
T->Left = InsertAVL(T->Left, X);
if (GetHeight(T->Left) - GetHeight(T->Right) == 2)
if (X < T->Left->Data)
T = SLR(T);
else
T = DLR(T);
} else if (X > T->Data) {
T->Right = InsertAVL(T->Right, X);
if (GetHeight(T->Right) - GetHeight(T->Left) == 2)
if (X > T->Right->Data)
T = SRR(T);
else
T = DRR(T);
}
// else X == T->Data的情况,不做任何事
T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1;
return T;
}
void PreOrder(struct AVLNode*T){
if(T!=NULL){
printf("%d ",T->Data);
PreOrder(T->Left);
PreOrder(T->Right);
}
}
void InOrder(struct AVLNode*T){
if(T!=NULL){
InOrder(T->Left);
printf("%d ",T->Data);
InOrder(T->Right);
}
}
void PostOrder(struct AVLNode*T){
if(T!=NULL){
PostOrder(T->Left);
PostOrder(T->Right);
printf("%d ",T->Data);
}
}
int main(){
int i,j;
struct AVLNode*T;
T=NULL;
for(i=0;i<6;i++){
scanf("%d",&j);
T=InsertAVL(T,j);
}
printf("\n");
printf("先序:");PreOrder(T);
printf("\n");
printf("中序:");InOrder(T);
printf("\n");
printf("后序:");PostOrder(T);
printf("\n");
return 0;
}
2、编写程序,从键盘输入6个整数,逐个插入到AVL树中,在每次插入时重新平衡。根据你输入的整数序列,在草稿纸上画出该AVL树,遍历输出该树并检查结果是否正确。
最新推荐文章于 2022-11-18 15:11:51 发布