最近恶补数据结构,不过抱着小侄女实在复习不进去。。。这才复习完树
当时对于平衡树就没有一个系统的了解
具体的感念就不贴了,仔细说一说如何调整平衡二叉树
如果插入破坏了原有的平衡,“麻烦结点”在发现者右子树的右边,因而叫 RR 插入,需要RR 旋转(右单旋)
做如下调整
“麻烦结点”在发现者左子树的左边,因而叫 LL 插入,需要LL 旋转(左单旋)
“麻烦结点”在左子树的右边,因而叫 LR 插入,需要LR 旋转
“麻烦结点”在右子树的左边,因而叫 RL 插入,需要RL 旋转
每次插入只要根据上面的情况 做相应的调整就好了~
下面附上AVL的实现代码 :
typedef struct AVLTreeNode *AVLTree;
typedef struct AVLTreeNode{
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
AVLTree AVL_Insertion(ElementType X,AVLTree T)
{{ /* { /* 将 X插入 AVLAVL 树 T中,并且返回调整后的AVLAVL 树 */
if(!T){if ( !T ) { /* 若插入空树 ,则新建包含一个结点的树*/
T= (AVLTree)malloc(sizeof(struct AVLTreeNode));
T->Date = X;
T->Height = 0;
T->Left = T->Right =NULL;
}
else if(XDate){//插入T的左子树
T->Left = AVL_Insertion(X,T->Left);
if(GerHeight(T->Left)-GetHeight(T->Right)==2)
//需要左转
if(XLeft->Data)
T=SingleLeftRotation(T);//左单旋
else
T= DoubleLeftRight(T);//左右双旋
}
else if(X>T->Date){//插入T的右子树
T->Right =AVL_Insertion(X,T->Right);
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;
return T;
}
AVLTree SingleLeftRotation(AVLTree A)
{
//A必须有一个左子结点B
//将A与B做左单旋 , 更新AB的高度 , 返回新的根节点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
//将AB与C 做两次单选,返回新的节点C
A->Left = SingleRightRotation(A->Left);//将BC做右单旋,返回C
return SingleLeftRotation(A);//将AC做左单旋,C返回
}