二叉树-已知前序遍历和中序遍历,求后序遍历(2017北邮机试)

题目:输入二叉树的前序和中序遍历结果,输出二叉树后序遍历结果。
输入格式:
第一行为二叉树的前序遍历结果
第二行为二叉树的中序遍历结果
输出格式:
二叉树后序遍历结果
Example:
Inputs:
426315
623415
Outputs:
632514ios

分析:

前序遍历顺序为根左右中序遍历结果为左根右。前序遍历结果与中序遍历结果长度一致。算法

前序遍历首个为根,找到该根在中序遍历结果中的位置。就能够把树分为左子树与右子树。这样递归调用该函数,数据结构

先访问左子树,再访问右子树,最后输出根便可。函数

所用树及部分信息

代码:

/*
Project: 二叉树(BiTree)-北邮2017真题
Date:    2019/01/19
Author:  Frank Yu
题目:输入二叉树的前序和中序遍历结果,输出二叉树后序遍历结果。
输入格式:
第一行为二叉树的前序遍历结果
第二行为二叉树的中序遍历结果
输出格式:
二叉树后序遍历结果
Example:
Inputs:
426315
623415
Outputs:
632514
*/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
//由前序中序推出后序遍历
int PreIn2Post(string Preorder, string Inorder)
{
	int length = Preorder.length();
	if (length == 0)return 0;
	char Root = Preorder[0];
	int i = 0;
	for (; i<length; i++)
	{
		if (Root == Inorder[i])
			break;
	}
	cout <<endl<< "左子树前序遍历:" << Preorder.substr(1, i) << " 左子树中序遍历:" << Inorder.substr(0, i) << endl;
	PreIn2Post(Preorder.substr(1, i), Inorder.substr(0, i));//递归访问左子树
	cout << endl << "右子树前序遍历:" << Preorder.substr(i+1, length) << " 右子树中序遍历:" << Inorder.substr(i + 1, length) << endl;
	PreIn2Post(Preorder.substr(i + 1, length), Inorder.substr(i + 1, length));//递归访问右子树 
	cout << Root;//访问根 
	return 0;
}
//主函数
int main()
{
	string Preorder, Inorder;
	cin >> Preorder >> Inorder;
	PreIn2Post(Preorder, Inorder);
	cout << endl;
	return 0;
}

结果截图:

调试版
结果截图

更多数据结构与算法实现:数据结构(严蔚敏版)与算法的实现(含所有代码)spa

有问题请下方评论,转载请注明出处,并附有原文连接,谢谢!若有侵权,请及时联系。.net