题目详情
原题链接1
解题思路
上中下分别是:前序-中序-后序遍历。题目给定了前序-中序,可以求得原二叉树,从而求出后序遍历。
代码
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
int main()
{
typedef vector<int> ints;
stack<ints> med, fore;
stack<int> back;
size_t N; // numbers
cin >> N;
ints rawFore, rawMed;
while (rawMed.size() != N)
{
string tmp;
cin >> tmp;
if (tmp.size()==3)
{
//Pop
auto num = back.top();
back.pop();
rawMed.push_back(num);
}
else
{
auto num = 0;
cin >> num;
rawFore.push_back(num);
back.push(num);
}
}
med.push(rawMed);
fore.push(rawFore);
while (!med.empty())
{
auto subMed = med.top();
med.pop();
auto subFore = fore.top();
fore.pop();
if (subMed.empty())
continue;
const auto root = subFore.front();
back.push(root);
const auto iter = find(subMed.begin(), subMed.end(), root);
const size_t leftLen = iter - subMed.begin();
const auto rightLen = subMed.size() - leftLen - 1;
// push the medium order right
auto medRight = ints(subMed.begin() + 1 + leftLen, subMed.end());
// push the medium order left
auto medLeft = ints(subMed.begin(), subMed.begin() + leftLen);
// push the forward order right
auto foreRight = ints(subFore.begin() + 1 + leftLen, subFore.end());
// push the forward order left
auto foreLeft = ints(subFore.begin() + 1, subFore.begin() + 1 + leftLen);
if (!medLeft.empty())
{
med.push(medLeft);
fore.push(foreLeft);
}
if (!medRight.empty())
{
fore.push(foreRight);
med.push(medRight);
}
}
// print out the ints
while (!back.empty())
{
if (back.size()!=1)
cout << back.top() << " ";
else
cout << back.top() << endl;
back.pop();
}
system("pause");
return 0;
}