采用二叉树的数组表示方法,用stack保存一下当前节点编号,每push一下都将当前节点编号*2转向左子树,pop的时候就pop出来转向右子树。
#include <stdio.h>
#include <algorithm>
#include <stack>
#include <string.h>
using namespace std;
int n,k,current=1;
int Tree[10000];
int flag=0;
char op[2][10]={"Push","Pop"};
stack<int>s;
void postorder(int root){
if (Tree[root*2]!=-1) postorder(root*2);
if (Tree[root*2+1]!=-1) postorder(root*2+1);
if (flag==0){
flag=1;
printf("%d",Tree[root]);
}
else
printf(" %d",Tree[root]);
}
int main(){
//freopen("/Users/pantingting/Documents/code/data/input", "r", stdin);
memset(Tree, 0xff, sizeof(Tree));
scanf("%d",&n);
char tempop[10];
for (int i=0; i<2*n; i++) {
scanf("%s",tempop);
if (strcmp(tempop, op[0])==0) {
scanf("%d",&k);
Tree[current]=k;
s.push(current);
current*=2;
continue;
}
if (strcmp(tempop, op[1])==0) {
int temp=s.top();
s.pop();
current=temp*2+1;
}
}
postorder(1);
printf("\n");
return 0;
}