A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
Input
The input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.
Output
For each test case print a single line specifying the corresponding postorder sequence.
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
先序的第一个节点一定是根节点然后就再在中序中找到这个根节点然后根节点的左右分别为左右子树,左右子树为空的说明是叶节点需要记录一下。最后递归实现。
代码如下
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int pre[1010],post[1010],in[1010],id[1010],p;
void dfs(int l,int r,int L,int R)
{
int root=id[pre[l]];
int ls=root-L;//中序右子树
int rs=R-root;//中序左子树
if(ls)
dfs(l+1,l+root-1,L,root-1);
if(rs)
dfs(l+ls+1,r,root+1,R);
post[++p]=pre[l];//当左右子树都是空的说明是叶节点,记录
}
int main()
{
int n;
while(~scanf("%d",&n)&&n)
{
p=0;
for(int i=1;i<=n;i++)
scanf("%d",&pre[i]);
for(int i=1;i<=n;i++)
{
scanf("%d",&in[i]);
id[in[i]]=i;
}
dfs(1,n,1,n);
for(int i=1;i<=n;i++)
{
if(i==1)
printf("%d",post[i]);
else
printf(" %d",post[i]);
}
printf("\n");
}
return 0;
}