题目
思路
使用前序遍历和中序遍历得到后序遍历,然后输出# 代码
#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> in, pre, post;
stack<int> s;
void postOrder(int root, int start, int end) {
if (start > end) return;
int i = start;
while (i < end && in[i] != pre[root]) ++i;
postOrder(root + 1, start, i - 1);
postOrder(root + i + 1 - start, i + 1, end);
post.emplace_back(pre[root]);
}
int main()
{
int n;
cin >> n;
string str;
for(int i =0;i<2*n;++i){
cin >> str;
if (str == "Pop") {
in.emplace_back(s.top());
s.pop();
}
else{
int num;
cin >> num;
s.push(num);
pre.emplace_back(num);
}
}
postOrder(0, 0, n - 1);
cout << post[0];
for (int i = 1; i < n; ++i)
cout << " " << post[i];
return 0;
}