平衡二叉树的创建过程

#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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值