Data Structures and Algorithms (English)
#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
#define Max 1000
int pre[Max];
int in[Max];
int post[Max];
void solve(int preL, int inL, int postL, int n) {
if (n == 0) return;
if (n == 1) { post[postL] = pre[preL]; return; }
int i;
int L;
int R;
int root = pre[preL];
post[postL + n - 1] = root;
for (i = 0; i < n; i++) {
if (in[inL+i] == root) break;
}
L = i;
R = n - L - 1;
solve(preL + 1, inL, postL, L);
solve(preL + L+1, inL+L+1, postL+L, R);
}
int main() {
char str[10];
int n;
int number;
stack<int> s;
int i=0, j=0;
scanf("%d", &n);
while(j<n){
scanf("%s", str);
if (strcmp(str, "Push") == 0) {
scanf("%d", &number);
pre[i] = number;
s.push(number);
i++;
}
else if (strcmp(str, "Pop") == 0) {
in[j] = s.top();
s.pop();
j++;
}
}
solve(0, 0, 0, n);
for (int i = 0; i < n; i++) {
printf("%d", post[i]);
if(i!=n-1) printf(" ");
}
return 0;
}