//注意 注意 注意 这里边的什么什么型的树,都是我自己理解的,不是真的
左单旋
前期准备活动
typedfy struct AVLNode * Position;
typedfy Position AVLTree;
typedfy struct AVLNode{
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
} ;
int Max(int a,int b){
return a>b?a:b;
}
左单旋
AVLTree SingleftRotation(AVLTree p){//左单旋
AVLTree x=p->Left;//A必须有一个左子树节点B
p->Left=x->Right;
x->Right=p;
p->Height=Max(GetHeight(p->Left),GetHeight(p->Right))+1;//更新树的高度
x->Height=Max(GetHeight(x->Left),p->Height)+1;
return x;
}
RL旋转
AVLTree DoubleLeftRightRotation(AVLTree g){// g必须有一个左子树p,p 必须要有一个右子树x
//p和x做一次右RL单旋,把x返回
g->Left=SingleRightRotation(g->Left);
//将g和x做左单旋,x被返回
return SingLeftRotation(g);
}
这就是所谓的左单旋,和右单旋
平衡二叉树的插入
AVLTree InSert(AVLTree T,ElementType X){
if(!T){//如果是空树,直接插入
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->Data=X;
T->Height=1;//先设好高度
T->Left=T->Right=NULL;
}
else if(X<T->Data){//如果要插入左子树
T->Left=TnSert(T->Left,X);//递归下去
if(GetHeight(T->Left)-GetHeight(T->Right)==2)//不平衡了
if(X<T->Left->Data)//LL型
T=SingleLeftRotation(T);
else//LR型
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)//RR型
T=SingleRightRotation(T);
else//RL型
T=DoubleRightLeftRotation(T);
}
T->Height=Max(GetHeight(T->Left),GetHeight(T->Right))+1;//不要忘了还要更新树的高度
return T;
}