构造binary tree,然后后序遍历输出。
构造:记录当前结点p,若读入为Push i,则i为p的child,判断为左还是右child;若读入为Pop,则当前结点没有left child and(or) right child,然后寻找下一个right child未link的结点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #include <cstdio> #include <cstring> struct{ int fa,l,r; }t[31]; int n; int p; //当前结点 bool first=true; void postorder(int i){ if(i<=0) return; postorder(t[i].l); postorder(t[i].r); if(first){ printf("%d",i); first=false; } else printf(" %d",i); } int main(){ scanf("%d",&n); char str[10]; for(int i=0;i<=n;i++) t[i].l=t[i].r=0; //初始化为0,表示没有link child p=0; //头结点 while(scanf("%s",str)!=EOF){ if(strcmp(str,"Push")==0){ int child; scanf("%d",&child); if(t[p].l==0) t[p].l=child; else t[p].r=child; t[child].fa=p; p=child; } else{ //Pop if(t[p].l==0){ //当前结点的left child未link,则link为虚结点-1,当前结点不变 t[p].l=-1; } else{ //left child 已link为虚结点或真结点 t[p].r=-1; while(t[p].r) p=t[p].fa; //寻找left child 未link的结点为当前结点 } } } postorder(t[0].l); return 0; } |