Root of AVL Tree——二叉平衡树

1066 Root of AVL Tree (25分)

输入样例1

5
88 70 61 96 120

输出样例1

70

输入样例2

7
88 70 61 96 120 90 65

输出样例2

88

运行截图

在这里插入图片描述

代码

#include <iostream>
using namespace std;
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
    int data;
    AVLTree Left,Right;
    int Height;
};
int GetHeight(AVLTree A){
    int Height=0;
    if (A){
        Height=max(GetHeight(A->Left),GetHeight(A->Right));
    }
    return ++Height;
}
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 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 DoubleLeftRightRotation ( AVLTree A )
{ 
    A->Left = SingleRightRotation(A->Left);
    return SingleLeftRotation(A);
}
AVLTree DoubleRightLeftRotation ( AVLTree A )
{
    A->Right = SingleLeftRotation(A->Right);
    return SingleRightRotation(A);
}
AVLTree Insert(AVLTree T,int x){
    if(!T){
        T=(AVLTree)malloc(sizeof(struct AVLNode));
        T->data=x;
        T->Left= nullptr;
        T->Right= nullptr;
        T->Height=0;
    } 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);
        }
    } else if (x>T->data){
        T->Right=Insert(T->Right,x);
        if (GetHeight(T->Right)-GetHeight(T->Left)==2){
            if (x>T->Right->data)
                T=SingleRightRotation(T);
            else
                T=DoubleRightLeftRotation(T);
        }
    }
    T->Height=max(GetHeight(T->Left),GetHeight(T->Right))+1;
    return T;
}

int main()
{
    int n;
    cin>>n;
    int x;
    AVLTree A;
    while (n--){
        cin>>x;
        A=Insert(A,x);
    }
    cout<<A->data;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值