E - 数据结构实验之查找二:平衡二叉树
Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Sample Input
5 88 70 61 96 120
Output
70
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node*l,*r;
int d;
};
int max(int x,int y)
{
return x>y?x:y;
}
int deep(struct node*root)
{
if(root==NULL)
return 0;
else
return root->d;
}
struct node*LL(struct node*root)
{
struct node*p=root->l;
root->l=p->r;
p->r=root;
p->d=max(deep(p->l),deep(p->r))+1;
root->d=max(deep(root->l),deep(root->r))+1;
return p;
};
struct node*RR(struct node*root)
{
struct node*p=root->r;
root->r=p->l;
p->l=root;
p->d=max(deep(p->l),deep(p->r))+1;
root->d=max(deep(root->l),deep(root->r))+1;
return p;
};
struct node*RL(struct node*root)
{
root->r=LL(root->r);
return RR(root);
};
struct node*LR(struct node*root)
{
root->l=RR(root->l);
return LL(root);
};
struct node*cre(struct node*root,int x)
{
if(root==NULL)
{
root=(struct node*)malloc(sizeof(struct node));
root->data=x;
root->r=root->l=NULL;
root->d=0;
}
else if(x>root->data)
{
root->r=cre(root->r,x);
if(deep(root->r)-deep(root->l)>1)
{
if(x>root->r->data)
root=RR(root);
else
root=RL(root);
}
}
else if(x<root->data)
{
root->l=cre(root->l,x);
if(deep(root->l)-deep(root->r)>1)
{
if(x<root->l->data)
root=LL(root);
else
root=LR(root);
}
}
root->d=max(deep(root->l),deep(root->r))+1;
return root;
};
int main()
{
int n,i,x;
struct node*root=NULL;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
root=cre(root,x);
}
printf("%d\n",root->data);
return 0;
}