C++ 利用二叉树的 前序遍历 与 中序遍历,求出 后序遍历结果

C++ 利用二叉树的 前序遍历 与 中序遍历,求出 后序遍历结果

1、题目描述

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

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 prelidx, int preridx, int inlidx, int inridx, string preStr, string inStr, string& ans)
{
	int pos = getPos(preStr[prelidx], inStr);//以前序中节点找寻中序中的位置,以此判断当前根节点的左右子树长度

	int tmpl = pos - inlidx;//左子树的长度
	int tmpr = inridx - pos;//右子树的长度

	if (pos > inlidx)
		func(prelidx + 1, prelidx + tmpl, inlidx, pos - 1, preStr, inStr, ans);
	if (pos < inridx)
		func(preridx - tmpr + 1, preridx, pos + 1, inridx, preStr, inStr, ans);

	ans.push_back(preStr[prelidx]);
}
string postorderString(string postorderString, string inorderString)
{
	int sz = inorderString.size();
	string ans;
	func(0, sz - 1, 0, sz - 1, postorderString, inorderString, ans);
	return ans;
}

int main()
{
	string preStr = "ABEFCD";
	string inStr = "EBFADC";
	string ans = postorderString(preStr, inStr);
	cout << "后序遍历结果为:";
	cout << ans << endl;
	return 0;
}

2.3 运行结果

在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编写程解决的问题是根据给定的二叉树结果,该二叉树的后结果。 解决这个问题的一种常用方法是通过递归来构建二叉树。具体步骤如下: 1. 首先,根据的结果确定根节点。的第一个元素即为根节点。 2. 然后,在结果找到根节点的位置,将结果分为左子树和右子树。 3. 接下来,分别对左子树和右子树进行递归操作,得到左子树的后结果和右子树的后结果。 4. 最后,将根节点放在后结果的最后。 以下是一个示例代码实现: ```python def build_tree(preorder, inorder): if not preorder or not inorder: return [] root_val = preorder root = TreeNode(root_val) root_index = inorder.index(root_val) left_preorder = preorder[1:root_index+1] left_inorder = inorder[:root_index] right_preorder = preorder[root_index+1:] right_inorder = inorder[root_index+1:] root.left = build_tree(left_preorder, left_inorder) root.right = build_tree(right_preorder, right_inorder) return root def postorder_traversal(root): if not root: return [] result = [] result.extend(postorder_traversal(root.left)) result.extend(postorder_traversal(root.right)) result.append(root.val) return result # 示例调用 preorder = [1, 2, 4, 5, 3, 6, 7] inorder = [4, 2, 5, 1, 6, 3, 7] root = build_tree(preorder, inorder) postorder = postorder_traversal(root) print(postorder) ``` 输结果为:[4, 5, 2, 6, 7, 3, 1]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值