Problem Description
在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序遍历的结果。
Input
输入包含多组数据,每组数据格式如下。
第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
第二行包含n个整数,保证每个整数在int范围之内。
Output
为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
Sample Input
1 2 2 1 20
Sample Output
2 1 20
#include <stdio.h>
#include <stdlib.h>
int a[10001],k;
typedef struct node
{
int data;
struct node *lc;
struct node *rc;
}tree;
/*tree *creat()
{
tree *p;
p=(tree *)malloc(sizeof(tree));
p->lc=NULL;
p->rc=NULL;
return p;
}//建立叶子结点
void buildtree(tree *root,int a)
{
if(a>root->data)
{
if(root->rc!=NULL)
{
buildtree(root->rc,a);
}
else
{
root->rc=creat();
root->rc->data=a;
}
}//建立右子树
else
{
if(root->lc!=NULL)
{
buildtree(root->lc,a);
}
else
{
root->lc=creat();
root->lc->data=a;
}
}//建立左子树
}//建树*/
tree *creat(struct node *p,int x)
{
if(p==NULL)
{
p=(tree *)malloc(sizeof(tree));
p->data=x;
p->lc=NULL;
p->rc=NULL;
}
else
{
if(x<p->data) p->lc=creat(p->lc,x);
else p->rc=creat(p->rc,x);
}
return p;
}//此过程为上面两个自定义函数的结合
void middle(tree *root)
{
if(root!=NULL)
{
middle(root->lc);
a[k++]=root->data;//用数组记录数据,便于后续的输出
middle(root->rc);
}
}//中序遍历
int main()
{
int n,i,x;
tree *root;
while(scanf("%d",&n)!=EOF)
{
k=1;root=NULL;
for(i=1;i<=n;i++)
{
scanf("%d",&x);
/*if(i==1)
{
root=creat();
root->data=x;
}//建立整个数的根结点
else buildtree(root,x);
//如果用上面两个自定义函数的话,直接建立一个结构体就行,不用置空*/
root=creat(root,x);
}
middle(root);
for(i=1;i<=k-1;i++)
{
if(i==k-1) printf("%d\n",a[i]);
else printf("%d ",a[i]);
}
}
return 0;
}