平衡二叉树(c++实现)

#include <iostream>
using namespace std;
typedef struct AVLNode* Position;
typedef Position AVLTree;//AVL树类型
typedef int ElementType ;
typedef struct AVLNode {
    ElementType Data;//结点数据
    AVLTree Left;//指向左子树
    AVLTree Right;//指向右子树
    int Height;//树高
};
int Max(int a, int b) {
    return a > b ? a : b;
}
int GetHeight(AVLTree BT) {
    int HL, HR, MaxH;
    if (BT) {
        HL = GetHeight(BT->Left);
        HR = GetHeight(BT->Right);
        MaxH = HL > HR ? HL : HR;
        return (MaxH + 1);
    }
    else return 0;
}
AVLTree Insert(AVLTree T, ElementType x) {
    if (!T) {
        T = new AVLNode;
        T->Data = x;
        T->Left = T->Right = NULL;
        T->Height = 1;
    }
    else if (x > T->Data) {//插入右子树
        T->Right = Insert(T->Right, x);
        if (GetHeight(T->Left) - GetHeight(T->Right) == -2) {
            if (x > T->Right->Data)T = SingleRightRotation(T);//右单旋
            else T = DoubleRightLeftRotation(T);//右-左双旋
        }
    }
    else if (x < T->Data) {
        //插入左子树
        T->Left = Insert(T->Left, x);
        if (GetHeight(T->Left) - GetHeight(T->Right) == 2) {
            if (x < T->Left->Data)T = SingleLeftRotation(T);//左单旋
            else T = DoubleLeftRightRotation(T);//右-左双旋
        }
    }
    T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1; 
    return T;
}
AVLTree SingleLeftRotation(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 DoubleLeftRightRotation(AVLTree A){//左-右双旋 
    A->Left = SingleRightRotation(A->Left);
    return SingleLeftRotation(A);
}
AVLTree SingleRightRotation(AVLTree A)//右单旋
{
    AVLTree B = A->Right;
    A->Right = B->Left;
    B->Left = A;
    A->Height = Max(GetHeight(A->Left), GetHeight(A->Right)) + 1;
    B->Height = Max(GetHeight(B->Right), A->Height) + 1;
    return B;
}
AVLTree DoubleRightLeftRotation(AVLTree A) {//右-左双旋
    A->Right = SingleLeftRotation(A->Right);
    return SingleRightRotation(A);
}
 

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值