数据结构实验之查找二:平衡二叉树
Time Limit: 400 ms
Memory Limit: 65536 KiB
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Sample Input
5 88 70 61 96 120
Sample Output
70
Hint
#include<bits/stdc++.h>
using namespace std;
struct node
{
int da, nheight;
node *l, *r;
};
int height(node *p)
{
if(!p) return -1;
return p->nheight;
}
node *ll(node *p)
{
node *p1;
p1 = p->l;
p->l = p1->r;
p1->r = p;
p->nheight = max(height(p->l), height(p->r))+1;
p1->nheight = max(height(p1->l), p->nheight)+1;
return p1;
}
node *rr(node *p)
{
node *p1;
p1 = p->r;
p->r = p1->l;
p1->l = p;
p->nheight = max(height(p->l), height(p->r))+1;
p1->nheight = max(height(p1->r), p->nheight)+1;
return p1;
}
node *lr(node *p)
{
p->l = rr(p->l);
return ll(p);
}
node *rl(node *p)
{
p->r = ll(p->r);
return rr(p);
}
node *in(node *p, int x)
{
if(!p)
{
p = new node;
p->da = x;
p->nheight = 0;
p->l = p->r = NULL;
}
else
{
if(x<p->da)
{
p->l = in(p->l, x);
if(height(p->l)-height(p->r)>1)
{
if(x<p->l->da)
p = ll(p);
else p = lr(p);
}
}
else if(x>p->da)
{
p->r = in(p->r, x);
if(height(p->r)-height(p->l)>1)
{
if(x<p->r->da)
p = rl(p);
else p = rr(p);
}
}
}
p->nheight = max(height(p->l), height(p->r))+1;
return p;
}
int main()
{
int n, i;
scanf("%d", &n);
node *root = NULL;
while(n--)
{
scanf("%d", &i);
root = in(root, i);
}
cout<<root->da<<endl;
}