链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=2040
Description:
给出一棵二叉树的中序和前序遍历,输出它的后序遍历。
Input
本题有多组数据,输入处理到文件结束。
每组数据的第一行包括一个整数n,表示这棵二叉树一共有n个节点。
接下来的一行每行包括n个整数,表示这棵树的中序遍历。
接下来的一行每行包括n个整数,表示这棵树的前序遍历。
3<= n <= 100
Output
每组输出包括一行,表示这棵树的后序遍历。
Sample Input
7
4 2 5 1 6 3 7
1 2 4 5 3 6 7
Sample Output
4 5 2 6 7 3 1
代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#define MAXN 10005
#define RST(N)memset(N, 0, sizeof(N))
using namespace std;
int inorder_table[MAXN];
int preorder_table[MAXN];
int position[MAXN], n;
void work( int in_l, int in_r, int pre_l, int pre_r)
{
int pos;
if(in_l == in_r) {
cout << inorder_table[in_l] << ' ';
return;
}
pos = position[preorder_table[pre_l]];
if(in_l <= ( pos - 1)) work(in_l, pos-1, pre_l+1, pos-in_l+pre_l);
if((pos + 1) <= in_r) work(pos+1, in_r, pre_r-in_r+pos+1, pre_r);
cout << inorder_table[pos] << ' ';
}
int main()
{
while(cin >> n) {
RST(inorder_table), RST(preorder_table), RST(position);
for(int i=1; i<=n; i++) {
cin >> inorder_table[i];
position[inorder_table[i]] = i;
}
for(int i=1; i<=n; i++) cin >> preorder_table[i];
work(1, n, 1, n);
cout << endl;
}
return 0;
}