HLG 2040 二叉树的遍历 (二叉树遍历之间的转换)

链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值