1132: 第八章:我们终究差了一厘米
Description
几年后,林静和陈孝正都出现在郑微面前,而工作后的郑微也纠葛在工作、感情甚至阴谋之中。
面对林静和陈孝正,郑薇该如何选择。。。
选择总是那么困难,每一个结点都有两种选择,这个不是“二叉树”吗?现在有一个二叉树,我们已知它的先序遍历的结果和中序遍历的结果。请你给出它的后序遍历结果。
Input
输入有多组数据,每组的第一行是一个n,表示这棵二叉树有n个结点
然后是两行,第一行是先序遍历的结果,第二行是中序遍历的结果。
Output
给出n个结点的后序遍历结果
Sample Input
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1
看学长的代码 太强了
Code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,tot;
int a[10000];
int b[10000];
void find(int x,int y)
{
if(x==y)
{
printf("%d",a[tot]);
if(tot!=0)
printf(" ");
tot++;
}
if(x<y)
{
int i,j=tot;
for(i=x; i<=y; i++)
{
if(a[tot]==b[i])
break;
}
tot++;
find(x,i-1);//左根
find(i+1,y);//右根
printf("%d",a[j]);
if(j!=0)
printf(" ");
}
}
int main()
{
while(~scanf("%d",&n))
{
for(int i=0; i<n; i++)scanf("%d",&a[i]);
for(int i=0; i<n; i++)scanf("%d",&b[i]);
tot=0;
find(0,n-1);
printf("\n");
}
return 0;
}