push对应着前序遍历,pop对应中序遍历,然后根据前序中序来推后序。
#include <iostream>
#include <stack>
using namespace std;
int post_idx, n;
int N;
void solve(int pre[], int in[], int n)
{
if (n < 0)
return;
if (n > 1)
{
int idx;
for (idx = 0; idx != n; ++idx)
if (in[idx] == pre[0])
break;
int pre_t[31], in_t[31];
for (int i = 0; i != idx; ++i)
{
in_t[i] = in[i];
pre_t[i] = pre[i + 1];
}
if (idx != 0)
solve(pre_t, in_t, idx);
for (int i = 0; i != n - idx - 1; ++i)
{
pre_t[i] = pre[i + 1 + idx];
in_t[i] = in[i + idx + 1];
}
if (n - idx - 1 != 0)
solve(pre_t, in_t, n - idx - 1);
}
cout << pre[0];
if (n != N)
cout << ' ';
}
int main(void)
{
int pre_order[31];
int in_order[31];
int post_order[31];
stack<int> s;
string op;
int m;
int pre_idx = 0, in_idx = 0;
cin >> n;
N = n;
post_idx = 0;
while (pre_idx != n || in_idx != n)
{
cin >> op;
if ("Push" == op)
{
cin >> m;
s.push(m);
pre_order[pre_idx++] = m;
}
else
{
m = s.top();
s.pop();
in_order[in_idx++] = m;
}
}
solve(pre_order, in_order, n);
return 0;
}