数据结构实验之查找二:平衡二叉树

#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct bst {
    int d;
    bst *l,*r;
    int deep;
    bst() {
        l=r=NULL;
        deep=0;
    }
};
int deept(bst *p) {
    if(!p)
        return -1;
    return p->deep;
}
bst *LL(bst *p) {
    bst *q=p->l;
    p->l=q->r;
    q->r=p;
    p->deep=max(deept(p->r),deept(p->l))+1;
    q->deep=max(p->deep,deept(q->l))+1;
    return q;
}
bst *RR(bst *p) {
    bst *q=p->r;
    p->r=q->l;
    q->l=p;
    p->deep=max(deept(p->l),deept(p->r))+1;
    q->deep=max(deept(q->r),p->deep)+1;
    return q;
}
bst *LR(bst *p) {
    p->l=RR(p->l);
    return LL(p);
}
bst *RL(bst *p) {
    p->r=LL(p->r);
    return RR(p);
}
bst *InsertT(bst *p,int k) {
    if(!p) {
        p=new bst;
        p->d=k;
    }
    else if(k<p->d) {
        p->l=InsertT(p->l,k);
        if(deept(p->l)-deept(p->r)>1) {
            if(k<p->l->d)
                p=LL(p);
            else
                p=LR(p);
        }
    }
    else if(k>p->d) {
        p->r=InsertT(p->r,k);
        if(deept(p->r)-deept(p->l)>1) {
            if(k>p->r->d)
                p=RR(p);
            else p=RL(p);
        }
    }
    p->deep=max(deept(p->l),deept(p->r))+1;
    return p;
}

int main() {
    int n;
    scanf("%d", &n);
    bst *root=NULL;
    while(n--) {
        int x;
        scanf("%d", &x);
        root=InsertT(root,x);
    }
    printf("%d", root->d);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值