题目链接:https://vjudge.net/contest/358928#problem/A
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<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1e3+10;
int fir[N],mid[N];
int post[N],cnt,num;
void dfs(int x,int y)
{
int i=x;
while(fir[num]!=mid[i])
i++;
if(i>x)
{
num++;/*num来记录前序遍历的第num结点,遍历完左区间后,才遍历有区间,所以当执行if(i<y)右区间时,num的值会是(i-x+1)再继续增加*/
dfs(x,i-1);
}
if(i<y)
{
num++;
dfs(i+1,y);
}
post[cnt++]=mid[i];
}
int main()
{
int n;
while(~scanf("%d",&n))
{
num=1;
cnt=0;
for(int i=1; i<=n; i++)
scanf("%d",&fir[i]);
for(int i=1; i<=n; i++)
scanf("%d",&mid[i]);
dfs(1,n);
for(int i=0; i<cnt; i++)
printf("%d%c",post[i],i==cnt-1?'\n':' ');
}
return 0;
}
另一种写法:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,fir[2200],mid[2200];
int x,p;
void dfs(int t1,int t2,int tot)
{
if(t1>t2)
return;
int u;
for(int i=t1; i<=t2; i++)
{
if(fir[tot]==mid[i])/*在中序遍历中找到前序遍历的结点*/
{
u=i;
break;
}
}
dfs(t1,u-1,tot+1);
dfs(u+1,t2,tot+(u-t1+1));
p++;
if(p==0)
printf("%d",mid[u]);
else
printf(" %d",mid[u]);
}
int main()
{
while(~scanf("%d",&n)&&n)
{
p=-1;
for(int i=1; i<=n; i++)
scanf("%d",&fir[i]);/*前序遍历*/
for(int i=1; i<=n; i++)
scanf("%d",&mid[i]);/*中序遍历*/
dfs(1,n,1);
printf("\n");
}
return 0;
}