已知二叉树的前序、中序,求后序

二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。

输入输出格式

输入描述:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输出描述:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。

输入输出样例

输入样例#:
ABC
BAC
FDXEAG
XDEFAG
输出样例#:
BCA
XEDGAF
#include <iostream>
#include <string.h>
using namespace std;
void print(string pre, string in) {
	if (pre == "" || in == "")
		return;
	int pos = in.find(pre[0]);//在中序中找到根所在的位置
	//左子树
	print(pre.substr(1, pos), in.substr(0, pos));
	//右子树
	print(pre.substr(pos + 1), in.substr(pos + 1));
	//输出根
	cout << pre[0];
}
int main() {
	string pre, in;
	while (cin >> pre >> in) {
		print(pre, in);
		cout << endl;
	}
}
//已知后序、中序,求先序
void print(string post, string in) {
	if (post == "" || in == "")
		return;
	//输出根
	cout << post[post.size() - 1];
	int pos = in.find(post[post.size() - 1]);
	//左子树
	print(post.substr(0,pos), in.substr(0,pos));
	//右子树
	print(post.substr(pos, post.size() -pos- 1), in.substr(pos + 1));
}
int main() {
	string post, in;
	while (cin >> post >> in) {
		print(post, in);
		cout << endl;
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值