模板题目:建立二叉搜索树,先序和后序遍历
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *rchild,*lchild;
};
int a[1010],n;
vector<int>pre,premirror,post,postmirror;
void insert(node*&root,int x)
{
if(root==NULL)
{
root=new node;
root->data=x;
root->lchild=root->rchild=NULL;
return;
}
if(x<root->data)insert(root->lchild,x);
else insert(root->rchild,x);
}
void preorder(node*root)
{
if(root==NULL)return;
pre.push_back(root->data);
preorder(root->lchild);
preorder(root->rchild);
}
void preordermirror(node*root)
{
if(root==NULL)return;
premirror.push_back(root->data);
preordermirror(root->rchild);
preordermirror(root->lchild);
}
void postorder(node*root)
{
if(root==NULL)return;
postorder(root->lchild);
postorder(root->rchild);
post.push_back(root->data);
}
void postordermirror(node*root)
{
if(root==NULL)return;
postordermirror(root->rchild);
postordermirror(root->lchild);
postmirror.push_back(root->data);
}
bool issame(vector<int>p)
{
for(int i=0;i<p.size();i++)
{
if(a[i]!=p[i])return false;
}
return true;
}
void show(vector<int>p)
{
for(int i=0;i<p.size();i++)
{
printf("%d",p[i]);
if(i!=p.size()-1)printf(" ");
}
}
int main()
{
scanf("%d",&n);
node*root=NULL;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
insert(root,a[i]);
}
preorder(root);
preordermirror(root);
if(issame(pre)||issame(premirror))
{
printf("YES\n");
if(issame(pre))
{
postorder(root);
show(post);
}
else if(issame(premirror))
{
postordermirror(root);
show(postmirror);
}
}
else printf("NO\n");
return 0;
}