【问题描述】
二叉树是一种非常重要的数据结构,非常多其他数据结构都是基于二叉树的基础演变而来的。对于二叉树,深度遍历有前序、中序以及后序三种遍历方法。
三种基本的遍历思想为:
前序遍历:根结点 —> 左子树 —> 右子树
中序遍历:左子树—> 根结点 —> 右子树
后序遍历:左子树 —> 右子树 —> 根结点
比如,求以下二叉树的各种遍历
hhh.png
前序遍历:1 2 4 5 7 8 3 6
中序遍历:4 2 7 5 8 1 3 6
后序遍历:4 7 8 5 2 6 3 1
需要你编写程序解决的问题是:已知一个二叉树的前序遍历和中序遍历的结果,给出该二叉树的后序遍历的结果。
【输入形式】
#include <iostream>
using namespace std;
void postOrder(string a, string b)
{
if (a.empty())
return;
char root = a[0];
int k = b.find(root);
postOrder(a.substr(1, k), b.substr(0, k));
postOrder(a.substr(k + 1), b.substr(k + 1));
cout << root;
}
int main()
{
string a, b;
int n;
cin >> n;
while (n != 0)
{
cin >> a >> b;
postOrder(a, b);
cin >> n;
}
return 0;
}