平衡二叉树的创建过程

#include<stdio.h>

#include<stdlib.h>

typedef struct AVLNode* Position;

typedef Position AVLTree;//AVL树类型

struct AVLNode {

int Data;//节点数据

AVLTree Left;//指向左子树

AVLTree Right;//指向右子树

int Height;//树高 

};

int Max(int a, int b)

{

return a>b ? a : b;

}

int GetHeight(AVLTree A)

{

int HL, HR, MaxH;

if (A) {

HL = GetHeight(A->Left);

HR = GetHeight(A->Right);

MaxH = HL>HR ? HL : HR;

return (MaxH + 1);

}

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), GetHeight(B->Right)) + 1;

return B;

}

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(GetHeight(B->Left), GetHeight(B->Right)) + 1;

return B;

}

AVLTree DoubleLeftRightRotation(AVLTree A)

{

AVLTree B = A->Left;

//B进行右单旋

B = SingleRightRotation(B);

//对A进行左单旋

A = SingleLeftRotation(A);

return A;

}

AVLTree DoubleRightLeftRotation(AVLTree A)

{

A->Right = SingleLeftRotation(A->Right);

return A = SingleRightRotation(A);

}

AVLTree Insert(AVLTree T, int X)

{//将X插入AVL树T中,并且返回调整后的AVL树

if (!T) {//若插入空树,则新建一个包含节点的树

T = (AVLTree)malloc(sizeof(struct AVLNode));

T->Data = X;

T->Left = T->Right = NULL;

T->Height = 1;

}

else if (X<T->Data) {

//插入T的左子树

T->Left = Insert(T->Left, X);

//如果需要左旋

if (GetHeight(T->Left) – GetHeight(T->Left) == 2) {

if (X<T->Left->Data) {

T = SingleLeftRotation(T);//左单旋 

}

else {

T = DoubleLeftRightRotation(T);//左右双旋 

}

}

}//else if(插入左子树结束)

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(插入右子树)结束

//更新树高;

T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1;

return T;

}

AVLTree Print(AVLTree A)

{

if(A){

Print(A->Left );

printf(“%d “,A->Data );

Print(A->Right );

}else{

return NULL;

}

}

void Print1(AVLTree A)

{

if(A){

Print(A->Left );

printf(“%d “,A->Data );

Print(A->Right );

}

}

void PrintX(AVLTree A)

{

if(A){

printf(“%d “,A->Data );

Print(A->Left );

Print(A->Right );

}

}

void PrintH(AVLTree A)

{

if(A){

Print(A->Left );

Print(A->Right );

printf(“%d “,A->Data );

}

}

int main()

{

freopen(“C:\\Users\\DELL\\Desktop\\新建文件夹 (2)\\text.txt”,”r”,stdin);

AVLTree HeadTree;

HeadTree=NULL;

int i,a;

scanf(“%d”,&a);

for(i=0;a;i++){

HeadTree=Insert(HeadTree,a);

scanf(“%d”,&a);

}

printf(“中序遍历:\n”);

Print(HeadTree);

printf(“\n”);

Print1(HeadTree);

printf(“\n先序遍历:\n”);

PrintX(HeadTree);

printf(“\n后序遍历:\n”);

PrintH(HeadTree); 

return 0;

}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/qq_38191717/article/details/70185113
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞