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(TNULL)
{
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);
}