4.2 平衡二叉树
什么是平衡二叉树?
- 例:搜索树节点不同插入次序,将导致不同的深度和平均查找长度ASL
“平衡因子”(Balance Factor,简称BF): BF(T) = hL - hR, 其中hL和hR反别为T的左右子树的高度。
平衡二叉树(Balance Binary Tree)(AVL树)
空树,或者
任一结点左、右子树高度差的绝对值不超过1, 即|BF(T)|<= 1
- 结点总数为n的完全二叉树高度 h = θ ( l o g 2 n ) h = θ(log_2n) h=θ(log2n)
平衡二叉树的高度能达到 l o g 2 n log_2n log2n吗?
可以得到 n h = n h − 1 + n h − 2 + 1 n_h = n_{h-1} + n_{h-2}+1 nh=nh−1+nh−2+1
n h = F h + 2 − 1 n_h=F_{h+2}-1 nh=Fh+2−1(对 h >= 0) (F为斐波那契数列)
F i ≈ 1 5 ( 1 + 5 2 ) t F_{i} \approx \frac{1}{\sqrt{5}}\left(\frac{1+\sqrt{5}}{2}\right)^{t} Fi≈51(21+5)t
n h ≈ 1 5 ( 1 + 5 2 ) h + 2 − 1 n_{h} \approx \frac{1}{\sqrt{5}}\left(\frac{1+\sqrt{5}}{2}\right)^{h+2}-1 nh≈51(21+5)h+2−1
h = O ( l o g 2 n ) h = O(log_2n) h=O(log2n)
- 给定节点数二点为n的AVL树的最大高度为 O ( l o g 2 n ) O(log_2n) O(log2n) !
平衡二叉树的调整
-
RR旋转
不平衡的“发现者”是Mar,“麻烦结点”Nov在发现者右子树的右边,因而叫RR插入,需要RR旋转(右单旋)
-
LL旋转
“发现者”是Mar,“麻烦结点”Apr在发现者左子树的左边,因而叫LL插入,需要LL旋转(左单旋)
-
LR旋转
“发现者”是May, “麻烦结点”Jan在左子树的右边,因而叫LR插入,需要LR旋转
-
RL旋转
- 有时候插入元素即便不需要调整结构,也可能需要重新计算一些平衡因子
typedef struct AVLNode *Position;
typedef Position AVLTree; // AVL树类型
struct AVLNode{
ElementType Data;
AVLTree Left; // 指向左子树
AVLTree Right; // 指向右子树
int Height; // 树高
};
int Max( int a, int b)
{
return a > b ? a:b;
}
AVLTree SingleLeftRotation ( AVLTree A )
{
// 注意:A必须有一个左子结点B
//将A与B做左单旋,更新A与B的高度,返回新的根结点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做两次单旋,返回新的根结点C */
/* 将B与C做右单旋,C被返回 */
A->Left = SingleRightRotation(A->Left);
/* 将A与C做左单旋,C被返回 */
return SingleLeftRotation(A);
}
AVLTree Insert( AVLTree T, ElementType X )
{ /* 将X插入AVL树T中,并且返回调整后的AVL树 */
if ( !T ) { /* 若插入空树,则新建包含一个结点的树 */
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Data = X;
T->Height = 0;
T->Left = T->Right = NULL;
} /* if (插入空树) 结束 */
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 (插入左子树) 结束 */
else if ( X > T->Data ) {
/* 插入T的右子树 */
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 if (插入右子树) 结束 */
/* else X == T->Data,无须插入 */
/* 别忘了更新树高 */
T->Height = Max( GetHeight(T->Left), GetHeight(T->Right) ) + 1;
return T;
}