迷失の搜索树
Problem Description
小璐在机缘巧合之下获得了一个二叉搜索树,这个二叉搜索树恰好有n个节点,每个节点有一个权值,每个节点的权值都在[1,n]这个区间内,并且两两不相同,真是优美的性质啊
但是命运的不公又让她失去了这个二叉搜索树
幸运的是,她还记得自己丢失的二叉搜索树的前序遍历序列。
在丢了二叉搜索树之后,小璐无比想念她的这个树的后序遍历
那么问题来了,聪明的你在知道这个二叉搜索树的前序遍历的序列的情况下,能帮她找到这个二叉搜索树的后序遍历嘛?
Input
多组输入,以文件结尾
每组数据第一行为一个整数n,代表这个二叉搜索树的节点个数(1<=n<=100)
接下来一行n个整数,代表这个二叉搜索树的前序遍历序列
Output
输出n个整数
表示这个二叉树的后序遍历序列
Sample Input
5
4 2 1 3 5
Sample output
1 3 2 5 4
行吧,现在我依然想不明白为什么可以拿着先序遍历直接构建二叉排序树
可能来源于性质吧
#include <bits/stdc++.h>
using namespace std;
int n,cnt,a[1100];
struct node
{
int data;
struct node *l,*r;
};
struct node *creat(int x,struct node *root)
{
if(!root)
{
root=new node;
root->data=x;
root->l=root->r=NULL;
}
else
{
if(x<root->data)
root->l=creat(x,root->l);
else
root->r=creat(x,root->r);
}
return root;
};
void after(struct node *root)
{
if(root)
{
after(root->l);
after(root->r);
a[cnt++]=root->data;
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int x;cnt=0;
struct node *root;
root=NULL;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
root=creat(x,root);
}
after(root);
for(int i=0;i<n;i++)
{
if(i)
printf(" ");
printf("%d",a[i]);
}
printf("\n");
}
return 0;
}