/*
题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=477
题意:
给出二叉树的先序和中序遍历序列,输出后序遍历序列
查阅了的题解:
http://blog.csdn.net/mobius_strip/article/details/29639065
http://blog.csdn.net/YI__JIA/article/details/51223006
题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=477
题意:
给出二叉树的先序和中序遍历序列,输出后序遍历序列
查阅了的题解:
http://blog.csdn.net/mobius_strip/article/details/29639065
http://blog.csdn.net/YI__JIA/article/details/51223006
*/
//法一:
#include <iostream>
#include <string>
#include <stack>
using namespace std;
string pre, mid; // 分别表示先序、中序遍历序列
stack<char> ans;
void solve(int l1, int r1, int l2, int r2) // left1, right1, left2, right2,分别表示要遍历的树的先序和中序的起止位置
{
if (l1 > r1) return; //递归退出条件,退出时,先序和中序遍历都没有元素了,满足 l1 == r1 && l2 == r2,则这时按照后面的递归函数调用的参数,便可推理出退出递归的条件
ans.push(pre[l1]);
int root = l2;
while (pre[l1] != mid[root]) root++; //在中序中找到根节点
int size = root - l2; //左子树的大小
//因为是后序,又是用的栈结构,所以先递归右子树,再递归左子树
solve (l1 + 1 + size, r1, root + 1, r2);
solve (l1 + 1, l1 + size, l2, root - 1);
}
int main()
{
while (cin >> pre >> mid)
{
solve(0, (int)pre.size() - 1, 0, (int)mid.size() - 1);
while (!ans.empty())
{
cout << ans.top();
ans.pop();
}
cout << endl;
}
}
//法二:
/*
后来在网上搜能否优化一下时,突然发现,其实根本不需要栈结构的,只要转变一下递归顺序和输出根的顺序,即:
先遍历左子树,再遍历右子树,再输出根节点的元素,那就可以直接边复原树边输出了!而且,STL有性能瓶颈,所以...这种方法其实比法一更优!
*/
#include <iostream>
#include <string>
using namespace std;
string pre, mid; // 分别表示先序、中序遍历序列
void solve(int l1, int r1, int l2, int r2) // left1, right1, left2, right2,分别表示要遍历的树的先序和中序的起止位置
{
if (l1 > r1) return; //递归退出条件,退出时,先序和中序遍历都没有元素了,满足 l1 == r1 && l2 == r2,则这时按照后面的递归函数调用的参数,便可推理出退出递归的条件
int root = l2;
while (pre[l1] != mid[root]) root++; //在中序中找到根节点
int size = root - l2; //左子树的大小
//先递归左子树,再递归右子树,最后输出根节点元素
solve (l1 + 1, l1 + size, l2, root - 1);
solve (l1 + 1 + size, r1, root + 1, r2);
cout << mid[root];
}
int main()
{
while (cin >> pre >> mid)
{
int size = (int)pre.size() - 1;
solve(0, size, 0, size);
cout << endl;
}
}