PAT-A 1066 Root of AVL Tree (25 分)

该博客介绍了AVL树的基本概念,它是一种自平衡二叉搜索树,确保任何节点的两个子树高度差不超过1。当不平衡发生时,通过左旋、右旋、左右旋或右左旋四种旋转方式进行调整。文章提供了C++代码实现,展示如何根据插入序列构造AVL树并保持平衡,最后输出AVL树的根节点值。
摘要由CSDN通过智能技术生成

AVL树是一种自平衡二叉搜索树。

在AVL树中,任何节点的两个子树的高度最多相差 1 个。

如果某个时间,某节点的两个子树之间的高度差超过 1,则将通过树旋转进行重新平衡以恢复此属性。

现在,给定插入序列,请你求出 AVL 树的根是多少。

输入格式
第一行包含整数 N,表示总插入值数量。

第二行包含 N 个不同的整数,表示每个插入值。

输出格式
输出得到的 AVL 树的根是多少。

数据范围
1≤N≤20
输入样例1:
5
88 70 61 96 120
输出样例1:
70
输入样例2:
7
88 70 61 96 120 90 65
输出样例2:
88

AVL树的构造,构造后直接输出第一个节点即根的值即可。

#include <bits/stdc++.h>

using namespace  std;
struct node
{
    int data;
    struct node*l,*r;
};
int n;
int shendu(struct node*root)
{
    int ll,rr;
    if(root)
    {
        ll=shendu(root->l);
        rr=shendu(root->r);
        return max(ll,rr)+1;
    }
    return 0;
}
struct node*ll(struct node*root)
{
    struct node*p=root->l;
    root->l=p->r;
    p->r=root;
    return p;
}
struct node*rr(struct node*root)
{
    struct node*p=root->r;
    root->r=p->l;
    p->l=root;
    return p;
}
struct node*lr(struct node*root)
{
    root->l=rr(root->l);
    root = ll(root);
    return root;
}
struct node*rl(struct node*root)
{
    root->r=ll(root->r);
    root=rr(root);
    return root;
    
}
struct node*create(int shu,struct node*root)
{
    if(root==NULL)
    {
        root = new node;
        root->data=shu;
        root->l=NULL;
        root->r=NULL;
      
    }
    else if(shu<root->data)
    {
        root->l = create(shu,root->l);
    }
    else
    root->r = create(shu,root->r);
    if(shendu(root->l)-shendu(root->r)>1)
    {
        if(shendu(root->l->l)>shendu(root->l->r))
        {
            root = ll(root);
        }
        else
        root = lr(root);
    }
    else if(shendu(root->r)-shendu(root->l)>1)
    {
        if(shendu(root->r->l)>shendu(root->r->r))
        root = rl(root);
        else
        root = rr(root);
    }
    return root;
}
int main()
{
    cin >> n;
    struct node*root = NULL;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin >>x;
        root=create(x,root);
    }
    cout <<root->data;
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值