**浙大PAT甲级 1066 平衡二叉查找树

平衡二叉查找树的相关概念与旋转操作参考:点击打开链接

AC代码:

#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<list>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
using namespace std;
struct node
{
    int data;
    struct node* l=NULL;
    struct node* r=NULL;
    int h=0;
};
int heigt(node* k3)
{
    if(k3!=NULL)
        return k3->h;
    else
        return -1;
}
void SLL(node* &k2)
{
    node* k1;
    k1=k2->l;
    k2->l=k1->r;
    k1->r=k2;
    k2->h=max(heigt(k2->l),heigt(k2->r))+1;
    k1->h=max(heigt(k1->l),k2->h)+1;
    k2=k1;
}
void SRR(node* &k2)
{
    node* k1;
    k1=k2->r;
    k2->r=k1->l;
    k1->l=k2;
    k2->h=max(heigt(k2->l),heigt(k2->r))+1;
    k1->h=max(heigt(k1->r),k2->h)+1;
    k2=k1;
}
void DLR(node* &k3)
{
    SRR(k3->l);
    SLL(k3);
}
void DRL(node* &k3)
{
    SLL(k3->r);
    SRR(k3);
}
void Insert(node* &root,int x)
{
    if(root==NULL)
    {
        root=new node;
        root->data=x;
        return ;
    }
    if(root->data>x)
    {
        Insert(root->l,x);
        if(2==heigt(root->l)-heigt(root->r))
        {
            //cout<<1<<endl;
            if(x<root->l->data)
            {
                SLL(root);
            }
            else
            {
                DLR(root);
            }
        }
    }
    else if(root->data<x)
    {
        Insert(root->r,x);
        if(2==heigt(root->r)-heigt(root->l))
        {
            if(x>root->r->data)
            {
                SRR(root);
            }
            else
            {
                DRL(root);
            }
        }
    }
    root->h=max(heigt(root->l),heigt(root->r))+1;
}
int main()
{
    int n;
    scanf("%d",&n);
    node* root=NULL;
    for(int i=0;i<n;i++)
    {
        int d;
        scanf("%d",&d);
        Insert(root,d);
        //cout<<root->data<<endl;
    }
    printf("%d",root->data);

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值