AVL树

题目:(PAT)1066. Root of AVL Tree

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define cl(a,b) memset(a,b,sizeof(a));
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
using namespace std;
const int maxn=100;
const int inf=1<<28;

struct node{
    int data;
    int hight;
    node *lson,*rson;
    node(){lson=rson=NULL;hight=0;}
};
int geth(node *root){//计算节点左右的高度差
    return root?root->hight:-1;
}
bool isbalanced(node *root){//判断是不是平衡
    return abs(geth(root->lson)-geth(root->rson))<2;
}

node* LL(node* root){
    node *tmp=root->lson;
    root->lson=tmp->rson;
    tmp->rson=root;
    root->hight=max(geth(root->lson),geth(root->rson))+1;
    tmp->hight=max(geth(tmp->lson),geth(tmp->rson))+1;
    return tmp;
}
node *RR(node *root){
    node *tmp=root->rson;
    root->rson=tmp->lson;
    tmp->lson=root;
    root->hight=max(geth(root->lson),geth(root->rson))+1;
    tmp->hight=max(geth(tmp->lson),geth(tmp->rson))+1;
    return tmp;
}
node *RL(node *root){
    root->rson=LL(root->rson);
    return RR(root);
}
node *LR(node *root){
    root->lson=RR(root->lson);
    return LL(root);
}
node *insert(node *root,int v){
    if(root==NULL){
        root=new node();
        root->data=v;
        return root;
    }
    if(v>root->data){
        root->rson=insert(root->rson,v);
        if(!isbalanced(root)){
            if(v>root->rson->data){
                root=RR(root);
            }
            else {
                root=RL(root);
            }
        }
    }
    else {
        root->lson=insert(root->lson,v);
        if(!isbalanced(root)){
            if(v<root->lson->data){
                root=LL(root);
            }
            else {
                root=LR(root);
            }
        }
    }
    root->hight=max(geth(root->lson),geth(root->rson))+1;
    return root;
}

int main(){
    int n;
    scanf("%d",&n);
    node *root=NULL;
    for(int i=0;i<n;i++){
        int v;
        scanf("%d",&v);
        root=insert(root,v);
    }
    printf("%d\n",root->data);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值