#include <stdio.h>
typedef
int
ElementType;
typedef
struct
AvlNode *Position;
typedef
struct
AvlNode *AvlTree;
struct
AvlNode {
ElementType Element;
AvlTree Left;
AvlTree Right;
int
Height;
};
int
Max(
int
x,
int
y)
{
return
x > y ? x : y;
}
// 获得节点高度
int
Height(Position p)
{
if
(p == NULL)
return
-1;
else
return
p->Height;
}
// T跟左儿子进行右旋转
Position RightSingleRotate(Position T)
{
Position NewRoot;
NewRoot = T->Left;
T->Left = NewRoot->Right;
NewRoot->Right = T;
// 修改高度
T->Height = Max(Height(T->Left), Height(T->Right)) + 1;
NewRoot->Height = Max(Height(NewRoot->Left), T->Height) + 1;
return
NewRoot;
}
// T跟右儿子进行左旋转
Position LeftSingleRotate(Position T)
{
Position NewRoot;
NewRoot = T->Right;
T->Right = NewRoot->Left;
NewRoot->Left = T;
// 修改高度
T->Height = Max(Height(T->Left), Height(T->Right)) + 1;
NewRoot->Height = Max(Height(NewRoot->Right), T->Height) + 1;
return
NewRoot;
}
Position DoubleRotateWithLeft(Position T)
{
// 先左旋转
T->Left = LeftSingleRotate(T->Left);
// 再右旋转
return
RightSingleRotate(T);
}
Position DoubleRotateWithRight(Position T)
{
// 先右旋转
T->Right = RightSingleRotate(T->Right);
// 再左旋转
return
LeftSingleRotate(T);
}
AvlTree Insert(AvlTree T, ElementType x)
{
if
(T == NULL)
{
T =
malloc
(
sizeof
(
struct
AvlNode));
if
(T == NULL)
return
-1;
T->Element = x;
T->Left = T->Right = NULL;
T->Height = 0;
}
else
if
(x < T->Element)
{
T->Left = Insert(T->Left, x);
if
(Height(T->Left) - Height(T->Right) == 2)
if
(x < T->Left->Element)
T = RightSingleRotate(T);
// 左-左:右单旋转
else
T = DoubleRotateWithLeft(T);
// 左-右:左右双旋转
}
else
if
(x > T->Element)
{
T->Right = Insert(T->Right, x);
if
(Height(T->Right) - Height(T->Left) == 2)
if
(x > T->Right->Element)
T = LeftSingleRotate(T);
// 右-右:左单旋转
else
T = DoubleRotateWithRight(T);
// 右-左:右左双旋转
}
T->Height = Max(Height(T->Left), Height(T->Right)) + 1;
// 调整高度
return
T;
}
void
MiddleTraversal(AvlTree T)
{
if
(T == NULL)
return
;
MiddleTraversal(T->Left);
printf
(
"%d "
, T->Element);
MiddleTraversal(T->Right);
}
int
main()
{
AvlTree tree = NULL;
int
i;
for
(i = 1; i <= 16; i++)
tree = Insert(tree, i);
MiddleTraversal(tree);
return
0;
}
原文:http://blog.csdn.net/nestler/article/details/24991539