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;
}