AVL树的实现

struct AvlNode;
typedef struct AvlNode *Position;
typedef struct AvlNode *AvlTree;
int max(int a,int b);
static int Height(AvlTree T);
AvlTree singlerotatewithLeft(AvlTree K2);
AvlTree singlerotatewithRight(AvlTree K2);
AvlTree doublerotatewithRight(AvlTree K3);
AvlTree doublerotatewithLeft(AvlTree K3);
AvlTree Insert(int x,AvlTree T);
#include<stdio.h>
#include<stdlib.h>

struct AvlNode //定义树的结点
{
int Element;
AvlTree Right;
AvlTree Left;
int Height;
};

int max(int a,int b)
{
if(a>b||a==b)
return a;
else
return b;
}

int Height(Position P) //返回树P的高度
{
if(P==NULL)
return -1;
else
return P->Height;
}

Position singlerotatewithLeft(Position K2) //单旋转,把左边的树转到右边
{
Position K1;
K1=K2->Left;
K2->Left=K1->Right;
K1->Right=K2;
//更新K1和K2高度,先更新K2的高度,再更新K1的高度,因为旋转过后K2是K1的子树
K2->Height=max(Height(K2->Left),Height(K2->Right))+1;
K1->Height=max(Height(K1->Left),K2->Height)+1;
return K1;
}

AvlTree singlerotatewithRight(AvlTree K1) //单旋转,把右边的树转到左边
{
Position K2;
K2=K1->Right;
K1->Right=K2->Left;
K1=K2->Left;
return K2;
}

AvlTree doublerotatewithRight(AvlTree K3)
{
K3->Right=singlerotatewithLeft(K3->Right);
return singlerotatewithRight(K3);
}

AvlTree doublerotatewithLeft(AvlTree K3)
{
K3->Left=singlerotatewithLeft(K3->Left);
return singlerotatewithRight(K3);
}

AvlTree Insert(int x,AvlTree T)
{
if(TNULL)
{
T=(AvlTree)malloc(sizeof( struct AvlNode ));
if(T
NULL)
{
printf(“out of space”);
exit(0);
}
else
{
T->Element=x;
T->Height=0;
T->Left=NULL;
T->Right=NULL;
}
}
else
if(xElement)
{
T->Left=Insert(x,T->Left);
if(Height(T->Left)-Height(T->Right)==2)
{
if(xLeft->Element)
T=singlerotatewithLeft(T);
else
T=doublerotatewithLeft(T);
}
}
else
if(x>T->Element)
{
T->Right=Insert(x,T->Right);
if(Height(T->Right)-Height(T->Left)==2)
{
if(x>T->Right->Element)
T=singlerotatewithRight(T);
else
T=doublerotatewithRight(T);
}
}
T->Height = max(Height(T->Left),Height(T->Right))+1;
return T;
}
//在树中插入一些元素,并通过检查树的高度来检查AVL树是否得以实现
int main(){
AvlTree T=NULL;
T=Insert(9,T);
T=Insert(10,T);
T=Insert(7,T);
T=Insert(4,T);
T=Insert(3,T);
int a = Height(T);
printf("%d",a);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值