您的位置:首页 > 其它

平衡二叉树(AVL树)

2017-11-08 09:43 302 查看
平衡二叉树,也叫AVL树:

任一结点左右子树高度差绝对值不超过1的二叉搜索树。

typedef struct AVLTreeNode *AVLTree;
typedef struct AVLTreeNode{
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};


AVLTree AVL_Insertion ( ElementType X, AVLTree T )
{   /* 将 X 插入 AVL 树 T 中,并且返回调整后的 AVL 树 */
if(!T){  /* 若插入空树,则新建包含一个结点的树 */
T = (AVLTree)malloc(sizeof(struct AVLTreeNode));
T->Data = X;
T->Height = 0;
T->Left = T->Right = NULL;
}
else if(X < T->Data)
{  /* 插入 T 的左子树 */
T->Left = AVL_Insertion(X, T->Left);
if (GetHeight(T->Left) - GetHeight(T->Right)== 2)
{   /* 需要左旋 */
if (X < T->Left->Data)
T = SingleLeftRotation(T);/* 左单旋 */
else
T = DoubleLeftRightRotation(T); /* 左-右双旋 */
}
}
else if(X > T->Data)
{ /* 插入 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 SingleLe
4000
ftRotation (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), A->Height)+1;
return B;
}

AVLTree DoubleLeftRightRotation (AVLTree A)  //左-右双旋
{
A->Left = SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}


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), A->Height)+1;
return B;
}

AVLTree DoubleRightLeftRotation (AVLTree A)  //右-左双旋
{
A->Right = SingleLeftRotation(A->Right);
return SingleRightRotation(A);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: