Description
给出一棵二叉树的前序遍历序列和中序遍历序列,求后序遍历序列
Input
第一行为一整数n表示二叉树节点数,之后两行每行n个整数表示二叉树的前序遍历序列和中序遍历序列
Output
输出后序遍历序列
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
Solution
前序遍历序列的第一个元素即为根节点,在中序遍历序列中找到根节点即把中序遍历序列分为两部分,分别为左子树和右子树,知道两部分的长度即可得到这两部分的前序遍历序列,之后递归这两部分即可
Code
#include <stdio.h>
#include <string.h>
#define maxn 1111
int n,pre[maxn],in[maxn],post[maxn],id[maxn],res;//pre表示前序遍历序列,in表示中序遍历序列
void print(int a,int b,int c,int d)//a,b,c,d分别表示前序和中序遍历序列的起点和终点
{
int i=id[pre[a]];//根节点
int j=i-c;//中序遍历序列的左子树
int k=d-i;//中序遍历序列的右子树
if(j) print(a+1,a+j,c,i-1);//左子树非空则递归左子树
if(k) print(a+j+1,b,i+1,d);//右子树非空则递归右子树
post[res++]=pre[a];
}
int main()
{
while(~scanf("%d",&n))
{
res=0;
for(int i=0;i<n;i++)scanf("%d",&pre[i]);
for(int i=0;i<n;i++)scanf("%d",&in[i]),id[in[i]]=i;
print(0,n-1,0,n-1);
for(int i=0;i<n;i++)
printf("%d%c",post[i],i==n-1?'\n':' ');
}
return 0;
}