平衡二叉树
平衡因子: BF=hL - hR ,即左右树高的差。
定义: 空树,或者平衡因子 | BF(T) |<=1
#define ElementType int;
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
ElementType Data;
AVLTree Left,Right;
int Height;
};
平衡二叉树的调整
左单旋
//左单旋
AVLTree SingleLeftRotation(AVLTree A){
//A必须有一个右结点B,A和B做左单旋,更新AB的树高,返回B
AVLTree B=A->Left;
B->Right=A;
A->Height=Max(GetTreeHeight(A->Left),GetTreeHeight(A->Right))+1;
B->Height=Max(GetTreeHeight(B->Left),GetTreeHeight(B->Right))+1;
return B;//平衡树的根结点更新成 B
}
右单旋
//右单旋
AVLTree SingleRightRotation(AVLTree A){
//A必须有一个左结点B,A和B做右单旋,更新AB的树高,返回B
AVLTree B=A->Right;
B->Left=A;
A->Height=Max(GetTreeHeight(A->Left),GetTreeHeight(A->Right))+1;
B->Height=Max(GetTreeHeight(B->Left),GetTreeHeight(B->Right))+1;
return B;//平衡树的根结点更新成 B
}
左右双旋
//左右双旋
AVLTree SingleLeftRightRotation(AVLTree A){
/* A必须有一个左子结点B,B必须有一个右子结点C
A和B做右单旋,A和C做左单旋
*/
A->Left=SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}
右左双旋
//右左双旋
AVLTree SingleRightLeftRotation(AVLTree A){
/* A必须有一个右子结点B,B必须有一个左子结点C
A和B做左单旋,A和C做右单旋
*/
A->Right=SingleLeftRotation(A->Right);
return SingleRightRotation(A);
}
插入
//向平衡树中插入新的元素,并且返回调整后的平衡树
AVLTree Insert(AVLTree T,ElementType X){
if(!T){//原树空,插入新结点
T=(AVLTree)malloc(sizeof(struct AVLNode));
T->Data=X;
T->Left=T->Right=NULL;
T->Height=0;
}else if(X<T->Data){
//向T的左子树插入X
T->Left=Insert(T->Left,X);
//需要左旋
if(GetTreeHeight(T->Left)-GetTreeHeight(T->Left)==2)
if(X<T->Left->Data)
T=SingleLeftRotation(T);//左单旋
else
T=SingleLeftRightRotation(T);//左右双旋
}else if(X>T->Data){
//向T的右子树插入X
T->Right=Insert(T->Right,X);
//需要右旋
if(GetTreeHeight(T->Left)-GetTreeHeight(T->Left)==-2)
if(X>T->Right->Data)
T=SingleRightRotation(T);//右单旋
else
T=SingleLeftRightLeftRotation(T);//右左双旋
}/*else if(X==T->Data),无需插入*/
//更新树高
T->Height=Max(GetTreeHeight(T->Left),GetTreeHeight(T->Right)) +1;
return T;
}