概念
- 二叉搜索树的查找效率与树的深度有关
- 平衡因子(BF):BF=HL-HR(HL——左子树高度;HR——右子树高度)
- 平衡二叉树(Balanced Binary Tree/AVL树):空树,或者任一结点左、右子树高度差的绝对值不超过1,即|BF(T) |≤ 1
平衡二叉树的高度
给定结点数为N的AVL树的最大高度为O(logN)
推导:
平衡二叉树的调整
typedef struct AVLNode* Position;
typedef Position AVLTree;
struct AVLNode{
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
AVLTree SingleLeftRotation(AVLTree A)
{
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),GetHeight(B->Right))+1;
return B;
}
AVLTree SingleRightRotation(AVLTree A)
{
AVLTree B=A->Right;
A->Right=B->Left;
B->Left=A;
A->Height=Max(GetHeight(A->Left),GetHeight(A->Right))+1;
B->Height=Max(GetHeight(B->Left),GetHeight(B->Right))+1;
return B;
}
AVLTree Double_LR_Rotation(AVLTree A)
{
/*A,B,C三个结点如上图所示排列,先对B,C做右单旋,返回C;再对A,C做左单旋,返回C*/
AVLTree B=A->Left;
A->Left=SingleRightRotation(B);
return SingleLeftRotation(A);
}
/*Double_RL_Rotation(AVLTree A)同理,省略*/
AVLTree Insert( AVLTree T, ElementType X )
{
/*插入X,调整为AVL*/
if(T==NULL){
T=(AVLTree)malloc(sizeof(struct AVLNode);
T->Data=X;
T->Height=0;
T->Left=T->Right=NULL;}
else if(T->Data<X){/*插入右树,可能RR,RL*/
T->Right=Insert(T->Right,X);
if((GetHeight(T->Left)-GetHeight(T->Right))==-2)
if(X>T->Right->Data) T=SingleRightRotation(T);
else T=Double_RL_Rotation(T);
}
else if(T->Data>X){/*插入左树,可能出现LL,LR*/
T->Left=Insert(T->Left,X);
if((GetHeight(T->Left)-GetHeight(T->Right))==2)
if(X<T->Left->Data) T=SingleLeftRotation(T);
else T=Double_LR_Rotation(T);
}
T->Height=Max(GetHeight(T->Left),GetHeight(T->Right))+1;
return T;
}