(p138)非递归完成二叉树的遍历
2016-02-25 19:32
106 查看
花了将近一个星期才搞懂了非递归遍历的方式,其中后序遍历真心麻烦,具体参考百度百科后序遍历和http://blog.csdn.net/cqnuztq/article/details/8896953
/* * source.c * * Created on: Feb 25, 2016 * Author: wing */ #include<stdio.h> #include<stdlib.h> #define maxsize 1000 struct node{ char n; struct node *l,*r; }; struct stack{ struct node **head; int top; }; int build(struct node **parent)/*递归建立二叉树*/ { char n; scanf("%c",&n); if (n=='#') { *parent=NULL; return 0; } else { *parent=(struct node *)malloc(sizeof(struct node)); (*parent)->n=n; build(&(*parent)->l); build(&(*parent)->r); return 0; } } int initstack(struct stack *st) { st->head=(struct node**)malloc(sizeof(struct node*)*(maxsize)); st->top=-1; return 0; } int push(struct stack *st,struct node *next) { st->head[++(st->top)]=next; return 0; } struct node *pop(struct stack *st) { return st->head[st->top--]; } int pretrav(struct node *root) { struct node *next; struct stack st; initstack(&st); next=root; while (next!=NULL||st.top>=0) { if (next!=NULL) { printf("%c ",next->n); push(&st,next); next=next->l; } else { next=pop(&st); next=next->r; } } free(st.head); return 0; } int intrav(struct node *root) { struct stack st; struct node *next; initstack(&st); next=root; while (next!=NULL||st.top>=0) { if (next!=NULL) { push(&st,next); next=next->l; } else { next=pop(&st); printf("%c ",next->n); next=next->r; } } free(st.head); return 0; } int postrav(struct node *root) { struct node *next,*prev; struct stack st; initstack(&st); next=root; while (next!=NULL||st.top>=0) { while(next!=NULL) { push(&st,next); next=next->l; } prev=NULL; while (st.top>=0) { next=st.head[st.top]; if (next->r==prev) { printf("%c ",next->n); prev=pop(&st); } else { next=next->r; break; } } if (st.top==-1) break; } return 0; } int main(void) { struct node **root; root=(struct node **)malloc(sizeof(struct node*)); build(root); printf("先序遍历:"); pretrav(*root); printf("\n中序遍历:"); intrav(*root); printf("\n后序遍历:"); postrav(*root); return 0; }
相关文章推荐
- 如何手动把pdf转换成word文档
- UIBezierPath 画线
- Live555源代码解读(9)
- python之强大的日志模块
- ElasticSearch——安全 Search Guard
- 将Lua解释器移植到STM32
- [Mac系统]python 使用qrcode模块
- Live555源代码解读(8)
- CodeForces 621 B. Wet Shark and Bishops(水~)
- 记录
- 设计模式总观
- 二叉排序树
- Hadoop集群_MapReduce初级案例
- BZOJ 1879: [Sdoi2009]Bill的挑战|状压DP
- 1294: [SCOI2009]围豆豆Bean 射线法+状压DP+spfa
- 导出EXCEL遇到问题
- 使用 robolectric 做单元测试
- Java并发-类库新组件 - CountDownLatch 理解
- 微软收购Xamarin,你怎么看?
- Live555源代码解读(7)