【题意】输入n,接下来输入n个数字,由中n个数字构建二叉排序树(二叉搜索树),并输出其前中后序遍历结果。
【样例输入输出】
输入
5
1 6 5 9 8
输出
16598
15689
65981
【注意】输入可能有重复元素,但是输出的二叉遍历序列中重复元素不用输出
#include<iostream>
#include<stack>
#include<string.h>
#include<iomanip>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
struct Node
{
Node*l;
Node*r;
int c;
}Tree[50];
int loc;
Node* create()
{
Tree[loc].l=Tree[loc].r=NULL;
return &Tree[loc++];
}
void inorder(Node* T)
{
if(T->l!=NULL)
inorder(T->l);
cout<<T->c;
if(T->r!=NULL)
inorder(T->r);
}
void preorder(Node* T)
{
cout<<T->c;
if(T->l!=NULL)
preorder(T->l);
if(T->r!=NULL)
preorder(T->r);
}
void postorder(Node* T)
{
if(T->l!=NULL)
preorder(T->l);
if(T->r!=NULL)
preorder(T->r);
cout<<T->c;
}
Node* Insert(Node*T,int a)// 易出错
{
if(T==NULL)
{
T=create();
T->c=a;
return T;
}
else if(a>T->c)
{
T->r=Insert(T->r,a);
}
else if(a<T->c)
{
T->l=Insert(T->l,a);
}
return T;
}
int main(int argc, char const *argv[])
{
int n,temp;
loc=0;
Node* T=NULL;
cin>>n;
while(n--)
{
cin>>temp;
T=Insert(T,temp);
}
preorder(T);cout<<endl;
inorder(T);cout<<endl;
postorder(T);cout<<endl;
return 0;
}