题目描述
在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序遍历的结果。
输入
输入包含多组数据,每组数据格式如下。
第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
第二行包含n个整数,保证每个整数在int范围之内。
输出
为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
题解:二叉排序树就是比根节点小的放在左子树上,比根节点大的放到右子树上。
示例输入#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *lchild,*rchild;
}Tree;
int key;
int a[1001];
Tree *creat(Tree *root,int x)
{
if(!root)
{
root=new Tree();
root->data=x;
root->lchild=root->rchild=NULL;
}
else
{
if(x<root->data)
root->lchild=creat(root->lchild,x);
else
root->rchild=creat(root->rchild,x);
}
return root;//这里要有返回值,当然如果你引用的话,就不用返回值了
}
void mid(Tree *root)
{
if(root)
{
mid(root->lchild);
a[key++]=root->data;//注意输出形式
mid(root->rchild);
}
}
int main()
{
int T,i,x;
while(cin>>T)
{
key=0;
Tree *root=NULL;//这里root最好附空值,目的是建立根节点,好比较。
for(i=1;i<=T;i++)
{
cin>>x;
root=creat(root,x);
}
mid(root);
for(i=0;i<key;i++)
{
if(i==0)
cout<<a[i];
else
cout<<" "<<a[i];
}
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *lchild,*rchild;
}Tree;
int key;
int a[1001];
Tree *creat(Tree *root,int x)
{
if(!root)
{
root=new Tree();
root->data=x;
root->lchild=root->rchild=NULL;
}
else
{
if(x<root->data)
root->lchild=creat(root->lchild,x);
else
root->rchild=creat(root->rchild,x);
}
return root;//这里要有返回值,当然如果你引用的话,就不用返回值了
}
void mid(Tree *root)
{
if(root)
{
mid(root->lchild);
a[key++]=root->data;//注意输出形式
mid(root->rchild);
}
}
int main()
{
int T,i,x;
while(cin>>T)
{
key=0;
Tree *root=NULL;//这里root最好附空值,目的是建立根节点,好比较。
for(i=1;i<=T;i++)
{
cin>>x;
root=creat(root,x);
}
mid(root);
for(i=0;i<key;i++)
{
if(i==0)
cout<<a[i];
else
cout<<" "<<a[i];
}
cout<<endl;
}
return 0;
}
1 2 2 1 20
示例输出
2 1 20