push的次序就是先序序列,pop的次序就是中序序列,据此获取后序序列
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>
using namespace std;
stack<int> s;
vector<int> pre_order, in_order, post_order;
void get_post(int preL, int preR, int inL, int inR);
int main(){
int N;
scanf("%d", &N);
int t = 2*N;
while(t--){
char op[5];
int num;
scanf("%s", op);
if(strcmp(op, "Push")==0){
scanf("%d", &num);
s.push(num);
pre_order.push_back(num);
}
else{
in_order.push_back(s.top());
s.pop();
}
}
get_post(0, N-1, 0, N-1);
for(int i=0; i<N; i++){
printf("%d", post_order[i]);
if(i<N-1) printf(" ");
}
return 0;
}
//根据先序、中序序列,输出后续序列。类似于根据先、中序还原二叉树的代码
void get_post(int preL, int preR, int inL, int inR){
if(preL>preR) return;
int k=0;
while(in_order[k]!=pre_order[preL]) k++;
int left_len = k - inL;
get_post(preL+1, preL+left_len, inL, k-1);
get_post(preL+left_len+1, preR, k+1, inR);
post_order.push_back(pre_order[preL]);
return;
}