C++ 利用 中序 与 后序,求出 前序

C++ 利用 中序 与 后序,求出 前序

1、题目描述

给出一个二叉树的中序与后序遍历结果,求出其前序遍历结果。如
输入:“EBFADC”,“EFBDCA”
输出:“ABEFCD”

2、解题

2.1 思路

思路之一,即通过中序与后序的遍历结果,先求出原二叉树的排列,然后再对二叉树作前序遍历。
思路之二,直接根据中序与后序结果,求出前序遍历结果。
下面的实现是基于第二个思路!

2.2 代码

#include<iostream>
#include<string>
using namespace std;

int getPos(char c, string inStr)
{
	int pos;
	for (pos = 0; pos < inStr.size(); pos++)
	{
		if (inStr[pos] == c)
			break;
	}
	return pos;
}
void func(int inlidx, int inridx, int postlidx, int postridx, string inStr, string postStr, string& ans)
{
	int pos = getPos(postStr[postridx], inStr);
	ans.push_back(postStr[postridx]);
	int tmpl = pos - inlidx;
	int tmpr = inridx - pos;
	if (pos > inlidx)
		func(inlidx, pos - 1, postlidx, postridx - tmpr - 1, inStr, postStr, ans);
	if (pos < inridx)
		func(pos + 1, inridx, postlidx + tmpl, postridx - 1, inStr, postStr, ans);
}
string preorderString(string inorderString, string postorderString)
{
	int sz = inorderString.size();
	string ans;
	func(0, sz - 1, 0, sz - 1, inorderString, postorderString, ans);
	return ans;
}

int main()
{
	string inStr = "EBFADC";
	string postStr = "EFBDCA";
	string ans = preorderString(inStr, postStr);
	cout << "前序遍历:";
	cout << ans << endl;
	return 0;
}

2.3 运行结果

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值