二叉树 由中序遍历和前序遍历推后序遍历

根据后序遍历’=‘左子树的后序遍历’+‘右子树的后序遍历’+‘根节点递归求解即可

char pre[maxn], in[maxn], post[maxn];

void Post(char* _pre, char* _in, int _len, int _root) {
	if (_len <= 0) return;
	int i = 0;
	while (_in[i] != _pre[0]) ++i;
	Post(_pre + 1, _in, i, _root - (_len - i - 1) - 1);
	Post(_pre + i + 1, _in + i + 1, _len - i - 1, _root - 1);
	post[_root] = _pre[0];
}

int main() {
	//std::ios::sync_with_stdio(0);
	//std::cin.tie(0);
#ifdef NIGHT_13
	freopen("in.txt", "r", stdin);
	//freopen("myout.txt", "w", stdout);
#endif
	scanf("%s%s", pre, in);
	int len = strlen(in);
	Post(pre, in, len, len - 1);
	printf("%s\n", post);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据二叉树中序遍历后序遍历输出前序遍历的方法如下: 1. 首先,我们知道前序遍历的顺序是:根节点 -> 左子树 -> 右子树。 2. 后序遍历的顺序是:左子树 -> 右子树 -> 根节点。 3. 中序遍历的顺序是:左子树 -> 根节点 -> 右子树。 根据以上信息,我们可以得出以下步骤来输出前序遍历: 1. 后序遍历的最后一个节点一定是根节点。 2. 在中序遍历中找到根节点的位置,将中序遍历分为左子树和右子树。 3. 根据中序遍历中左子树和右子树的节点数量,将后序遍历分为左子树和右子树。 4. 递归地对左子树和右子树进行相同的操作,直到只剩下一个节点。 5. 输出当前节点的值,然后递归地输出左子树和右子树的节点值。 下面是一个示例代码来实现这个过程: ```python def build_preorder(inorder, inorder_start, inorder_end, postorder, postorder_start, postorder_end): if inorder_start > inorder_end: return [] root_val = postorder[postorder_end] root_index = inorder.index(root_val) left_size = root_index - inorder_start right_size = inorder_end - root_index left_preorder = build_preorder(inorder, inorder_start, root_index - 1, postorder, postorder_start, postorder_start + left_size - 1) right_preorder = build_preorder(inorder, root_index + 1, inorder_end, postorder, postorder_end - right_size, postorder_end - 1) return [root_val] + left_preorder + right_preorder def get_preorder(inorder, postorder): return build_preorder(inorder, 0, len(inorder) - 1, postorder, 0, len(postorder) - 1) # 示例输入 inorder = [4, 2, 5, 1, 6, 3, 7] postorder = [4, 5, 2, 6, 7, 3, 1] preorder = get_preorder(inorder, postorder) print(preorder) ``` 输出结果为:[1, 2, 4, 5, 3, 6, 7]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值