向AVL树进行插入的非递归函数

根据书上的递归版本试着实现非递归版,关键是找到该插入的树叶的位置。(待更正)

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;
}

        

    原文作者:AVL树
    原文地址: https://blog.csdn.net/moses1213/article/details/42681547
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞