插入
typedef struct AVLNode *Position;
typedef Position AVLTree;
typedef struct AVLNode
{
ELementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
int MAX(int a,int b)
{
retuan a>b?a:b;
}
AVLTree Insert(AVLTree T,ElementType X)
{
/*将X插入AVl树T中,并且返回调整后的AVL树*/
if(!T)
{
/*若插入空树,则新建包含一个结点的树*/
T=(AVLTree)malloc(sizeof(sturct AVLNode));
T->Data=X;
T->Height=1;
T->Left=T->Right=NULL;
}
else if(X<T->Data)
{
/*插入T的左子树*/
T->Left=Insert(T->Left,X);
/*如果需要左旋*/
if(GetHeight(T->Left)-GetHeight(T->Right)==2)
{
if(X<T->Left->Data) T=SingleLeftRotation(T); /*左单旋*/
else T=DoubleLeftRightRotation(T); /*左-右双旋*/
}
}
else if(X>T->Data)
{
T->Right=Insert(T->Right,X);
if(GetHeight(T->Left)-GetHeight(T->Right)==-2)
{
if(X<T->Right->Data) T=SingleRightRotation(T);
else T=DoubleRightLeftRotation(T);
}
}
/*else X==T->Data,无需插入*/
/*更新树高*/
T->Height=Max(GetHeight(T->Left),GetHeight(T->Right))+1;
}
左单旋
AVLTree SingleLeftRRotation(AVLTree A)
{
/*注意:A必须有一个左子结点B*/
/*记得更新高度*/
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),A->Height)+1;
return B;
}
左-右双旋
AVLTree DoubleLeftRightRotation(AVLTree A)
{
/*注意:A必须有一个左子结点B,且B必须有一个右子结点C*/
/*将A、B、C做两次单旋*/
A->Left=SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}