平衡二叉树的插入

int Max(int a, int b){
    if(a>b)
        return a;
    else
        return b;
}
int GetHeight(AVLTree A){
    if(A==NULL)
        return 0;
    return A->Height;
}
AVLTree LeftRotate(AVLTree A){
    AVLTree B=A->Right;
    A->Right=B->Left;
    B->Left=A; //这里需要不断的去刷新height
    A->Height = Max(GetHeight(A->Left), GetHeight(A->Right)) + 1;//刷新一下子树的高度。
    B->Height = Max(GetHeight(B->Right), A->Height) + 1;//此函数是输一个老根的树,返回一个带有新根的树;这里算新根的高度
    return B;
}//左旋,适用于右右模式,可用于右左模式,左右模式

AVLTree RightRotate(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 RightLeftRotate(AVLTree A){
    A->Right = RightRotate(A->Right);
    return LeftRotate(A);
}
 
 
AVLTree LeftRightRotate(AVLTree A){
    A->Left = LeftRotate(A->Left);
    return RightRotate(A);
}
 
 
AVLTree Insert(AVLTree T,int X){
    if(!T){
        T=(AVLTree)malloc(sizeof(struct AVLNode));
        T->Key=X;
        T->Height=1;
        T->Left=T->Right=NULL;
    }
 
    else if(X<T->Key){ //插入左子树
        T->Left=Insert(T->Left,X);
        if(GetHeight(T->Left)-GetHeight(T->Right)>=2){
            if(X<T->Left->Key)//这一步看是左左模式还是左右模式
                T=RightRotate(T);
            else
                T=LeftRightRotate(T);
        }
    }
 
    else if(X>T->Key){
        T->Right=Insert(T->Right, X);
        if(GetHeight(T->Right)-GetHeight(T->Left)>=2){
            if (X>T->Right->Key)//这一步就是看是右右模式还是右左模式
                T=LeftRotate(T);
            else
                T=RightLeftRotate(T);
 
        }
    }
    T->Height=Max(GetHeight(T->Left), GetHeight(T->Right))+1;
    return T;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值