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;
}