1066. Root of AVL Tree (25)-PAT甲级真题

手搓AVL树的插入。

回去复习了一年前学的数据结构课本的15章,AVL树插入的平衡处理,有四种情况:LL旋转、LR选中、RR旋转、RL旋转

#include<bits/stdc++.h>
using namespace std;
struct node{
    int val;
    node *l,*r;
    node(int x):val(x),l(NULL),r(NULL){}
};

int height(node* root){
    if(root==NULL) return 0;
    return max(height(root->l),height(root->r))+1;
}

node* LL(node* root){
    node* temp=root->l;
    root->l=temp->r;
    temp->r=root;
    return temp;
}

node* RR(node* root){
    node* temp=root->r;
    root->r=temp->l;
    temp->l=root;
    return temp;
}

node* LR(node* root){
    root->l=RR(root->l);
    return LL(root);
}

node* RL(node* root){
    root->r=LL(root->r);
    return RR(root);
}

node* insert(node* root,int val){
    if(root==NULL)
        root=new node(val);
    else if(val<root->val){
        root->l=insert(root->l,val);
        if(height(root->l)-height(root->r)>=2){
            // 平衡操作
            if(val<root->l->val) root=LL(root);
            else root=LR(root);
        }
    }else{
        root->r=insert(root->r,val);
        if(height(root->r)-height(root->l)>=2){
            // 平衡操作
            if(val>=root->r->val) root=RR(root);
            else root=RL(root);
        }
    }
    return root;
}
int main(){
    int n,val;
    node* root=NULL;
    scanf("%d",&n);
    while(n--){
        scanf("%d",&val);
        root=insert(root,val);
    }
    printf("%d",root->val);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值