根据书上的递归版本试着实现非递归版,关键是找到该插入的树叶的位置。(待更正)
AvlTree Insert(ElementType X, AvlTree T)
{
AvlTree Tmp = T;
if(T == NULL)
{
T = malloc(sizeof(struct AvlNode));
if(T == NULL)
FatalError("Out of space!!!");
else
{
T->Element = X; T->Height = 0;
T->Left = T->Right = NULL;
}
}
while(!(Tmp->Left == Tmp->Right == NULL))
{
if(X < Tmp->Element)
Tmp = Tmp->Left;
if(X > Tmp->Element)
Tmp = Tmp->Right;
}
else if(X < Tmp->Element)
{
Tmp->Left = X;
if(Height(Tmp->Left) - Height(T->Right) == 2)
if(X < Tmp->Left->Element)
Tmp = SingleRotateWithLeft(Tmp);
else
Tmp = DoubleRotateWithLeft(Tmp);
else if(X > Tmp->Element)
{
Tmp->Right = X;
if(Height(Tmp->Right) - Height(T->Left) == 2)
if(X < Tmp->Right->Element)
Tmp = SingleRotateWithRight(Tmp);
else
Tmp = DoubleRotateWithRight(Tmp);
}
T->Height =Max(Height(T->Left), Height(T->Right)) + 1;
return T;
}