【PTA】Root of AVL Tree (25 分)

//就本题而言其实不更新树高也可以
#include <iostream>

using namespace std;

struct node
{
    int data;
    node* lchild;
    node* rchild;
    int height;
};

int Max(int a,int b){
    return a>b? a:b;
}

int GetHeight(node* root){
//递归求树高
    if(!root) return 0;
    else{
        return Max(GetHeight(root->lchild),GetHeight(root->rchild))+1;
    }
}


//LL、RR、LR、RL:改变子树位置,更新树高
node* singleLeftRotation(node* A){
    node* B=A->lchild;
    A->lchild=B->rchild;
    B->rchild=A;
//更新树高:使用当前改变后的子树最易
    A->height=Max(GetHeight(A->lchild),GetHeight(A->rchild))+1;
    B->height=Max(A->height,GetHeight(B->lchild))+1;

    return B;
}

node* singleRightRotation(node* A){
    node* B=A->rchild;
    A->rchild=B->lchild;
    B->lchild=A;
//更新树高:使用当前改变后的子树最易
    A->height=Max(GetHeight(A->lchild),GetHeight(A->rchild))+1;
    B->height=Max(A->height,GetHeight(B->rchild))+1;

    return B;
}

node* doubleLeftRightRotation(node* A){
//不能新建一个变量B对B修改,而要直接修改A->lchild的值
    A->lchild=singleRightRotation(A->lchild);
    return singleLeftRotation(A);
}
node* doubleRightLeftRotation(node* A){
//不能新建一个变量B对B修改,而要直接修改A->rchild的值
    A->rchild=singleLeftRotation(A->rchild);
    return singleRightRotation(A);
}


node* Insert(node* root,int x){
    if(!root){
        node* t=new node;
        t->data=x;
        t->height=0;
        t->lchild=t->rchild=NULL;
        root=t;
    }else{
        if(x<root->data){
            root->lchild=Insert(root->lchild,x);
            if(GetHeight(root->lchild)-GetHeight(root->rchild)==2){
//插在左子树的左or右子树上,应比较左子树的data
                if(x < root->lchild->data) root=singleLeftRotation(root);
                else root=doubleLeftRightRotation(root);
            }
        }
        else if(x>root->data){
            root->rchild=Insert(root->rchild,x);
            if(GetHeight(root->lchild)-GetHeight(root->rchild)==-2){
//插在右子树的左or右子树上,应比较右子树的data
                if(x > root->rchild->data) root=singleRightRotation(root);
                else root=doubleRightLeftRotation(root);
            }
        }
    }

    root->height=Max(GetHeight(root->lchild),GetHeight(root->rchild))+1;

    return root;
}

int main(){
    int N,tmp;
    cin>>N;
    node* root=NULL;
    for(int i=0;i<N;i++){
        cin>>tmp;
        root=Insert(root,tmp);
    }

    cout<<root->data;

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值