题目描述
输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。
输入
输入第一行包括一个整数n(1<=n<=100)。接下来的一行包括n个整数。
输出
可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。每种遍历结果输出一行。每行最后一个数据之后有一个空格。
样例输入
1
2
2
8 15
4
21 10 5 39
样例输出
2
2
2
8 15
8 15
15 8
21 10 5 39
5 10 21 39
5 10 39 21
特点:无重复数,左小右大
*&:查找修改
*:查找
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Btree{
int x;
Btree*left;
Btree*right;
Btree()
{
left=NULL;
right=NULL;
}
};
Btree*root;
int n,vis[10000];
void Insert(int x,Btree *&r)
{
if(r==NULL)
{
r=new Btree;
r->x=x;
}
else
{
if(x<r->x)
Insert(x,r->left);
else
Insert(x,r->right);
}
}
void pre(Btree*r)
{
if(r==NULL) return ;
cout<<r->x<<" ";
pre(r->left);
pre(r->right);
}
void in(Btree*r)
{
if(r==NULL) return;
in(r->left);
cout<<r->x<<" ";
in(r->right);
}
void pos(Btree*r)
{
if(r==NULL) return ;
pos(r->left);
pos(r->right);
cout<<r->x<<" ";
}
int Find(int x,Btree*r)
{
if(r==NULL) return 0;
if(r->x==x) return 1;
int left=Find(x,r->left);
int right=Find(x,r->right);
return left+right;
}
int main()
{
while(cin>>n)
{
root=NULL;
for(int i=0;i<n;i++)
{
int x;cin>>x;
if(!Find(x,root)) Insert(x,root);
}
pre(root);cout<<endl;
in(root);cout<<endl;
pos(root);cout<<endl;
}
return 0;
}