1086. Tree Traversals Again (25)
2016-03-10 16:46
519 查看
构造binary tree,然后后序遍历输出。
构造:记录当前结点p,若读入为Push i,则i为p的child,判断为左还是右child;若读入为Pop,则当前结点没有left child and(or) right child,然后寻找下一个right child未link的结点
构造:记录当前结点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; } |
相关文章推荐
- libdvbpsi源码分析(四)PAT表解析/重建
- PAT配置
- 什么是端口复用动态地址转换(PAT) 介绍配置实例
- MikroTik layer7-protocol
- PAT是如何工作的
- PAT 乙级题:1002. 写出这个数 (20)
- PAT (Advanced Level) Practise 1001-1010
- 数据结构学习与实验指导(一)
- PAT Basic Level 1001-1010解题报告
- 1001. 害死人不偿命的(3n+1)猜想
- 1002. 写出这个数
- 1032. 挖掘机技术哪家强
- 1001. 害死人不偿命的(3n+1)猜想 (PAT basic)
- 1002. 写出这个数(PAT Basic)
- 1004. 成绩排名(PAT Basic)
- 1006. 换个格式输出整数(PAT Basic)
- 1007. 素数对猜想(PAT Basic)
- 1008. 数组元素循环右移问题
- 1009. 说反话(PAT Basic)
- 1011. A+B和C(PAT Basic)