平衡二叉树失衡的四种情况:
AVL树节点声明:
struct AvlNode;
typedef struct AvlNode *Position;
typedef struct AvlNode *AvlTree;
struct AvlNode
{
ElementType Element;
AvlTree Left;
AvlTree Right;
int Height;
};
static int Height(Position P)
{
if (P == NULL)
return -1;
else
return P->Height;
}
对于第一种情况(左左)---(右右类似):
执行的变换代码为:
/* 左左情况下 */
static Position SingleRotateWithLeft(Position K2)
{
Position K1;
K1 = K2->Left;
K2->Left = K1->Right;
K1->Right = K2;
K2->Height = Max(Height(K2->Left), Height(K2->Right)) + 1;
K1->Height = Max(Height(K1->Left), Height(K1->Right)) + 1;
return K1; /* New Root */
}
/* 右右的情况下 */
static Position SingleRotateWithRight(Position K2)
{
Position K1;
K1 = K2->Right;
K2->Right = K1->Left;
K1->Left = K2;
K2->Height = Max(Height(K2->Left), Height(K2->Right)) + 1;
K1->Height = Max(Height(K1->Left), Height(K1->Right)) + 1;
return K1; /* New Root */
}
对于第三种情况(第四种类似):
执行的变换代码为:
/* 左右情况 */
static Position DoubleRotateWithLeft(Position K3)
{
/* Rotate between K1 and K2 */
K3->Left = SingleRotateWithRight(K3->Left);
/* Rotate between K3 and K2 */
return SingleRotateWithLeft(K3);
}
/* 右左情况 */
static Position DoubleRotateWithRight(Position K3)
{
/* Rotate between K1 and K2 */
K3->Right = SingleRotateWithRight(K3->Right);
/* Rotate between K3 and K2 */
return SingleRotateWithRight(K3);
}
向AVL树中插入节点的函数:
AvlTree Insert(Element x, AvlTree T)
{
if (T == NULL)
{
T = malloc(sizeof(struct AvlNode));
if (T == NULL)
printf("Out of space!\n");
else
{
T->Element = x;
T->Height = 0;
T->Left = T->Right = NULL;
}
}
else if (x < T->Element)
{
T->Left = Insert(x, T->Left);
if (Height(T->Left) - Height(T->Right) == 2)
if (x < T->Left->Element)
T = SingleRotateWithLeft(T);
else
T = DoubleRotateWithLeft(T);
}
else if (x > T->Element)
{
T->Right = Insert(x, T->Right);
if (Height(T->Right) - Height(T->Left) == 2)
if (x > T->Right->Element)
T = SingleRotateWithRight(T);
else
T = DoubleRotateWithRight(T);
}
/* Else x is in the tree already; we'll do nothing */
T->Height = Max(Height(T->Left), Height(T->Right)) + 1;
return T;
}