知识点讲解:
Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Sample
Input
5
88 70 61 96 120
Output
70
答案:
#include<bits/stdc++.h>
//#define ll long long
const int N = 1e5 + 10;
struct node
{
int data;
struct node *l,*r;
};
int flag;
using namespace std;
int geth(node *root) //获取树的深度
{
if(root==NULL)
return 0;
return max(geth(root->l),geth(root->r))+1;
}
node *ll(node *root)//右旋
{
struct node *p;
p=root->l;
root->l=p->r;
p->r=root;
return p;
}
node *rr(node *root)//左旋
{
struct node *p;
p=root->r;
root->r=p->l;
p->l=root;
return p;
}
node *lr(node *root)
{
root->l=rr(root->l);
root=ll(root);
return root;
}
node *rl(node *root)
{
root->r=ll(root->r);
root=rr(root);
return root;
}
node *create(struct node *root,int x) //建树
{
if(root==NULL)
{
struct node *t;
t=(struct node *)malloc(sizeof(struct node));
t->data=x;
t->l=NULL;
t->r=NULL;
return t;
}
if(x>root->data)
{
root->r=create(root->r,x);
}
else
{
root->l=create(root->l,x);
}
if(geth(root->l)-geth(root->r)>=2)
{
if(geth(root->l->l)>geth(root->l->r))
{
root=ll(root);
}
else
{
root=lr(root);
}
}
if(geth(root->r)-geth(root->l)>=2)
{
if(geth(root->r->l)>geth(root->r->r))
{
root=rl(root);
}
else
{
root=rr(root);
}
}
return root;
}
int main()
{
int n;
int x;
cin>>n;
node *tree=NULL;
while(n--)
{
cin>>x;
tree=create(tree,x);
}
cout<<tree->data<<endl;
return 0;
}