(p138)非递归完成二叉树的遍历
来源:互联网 发布:如何在淘宝上交水电费 编辑:程序博客网 时间:2024/06/07 03:24
花了将近一个星期才搞懂了非递归遍历的方式,其中后序遍历真心麻烦,具体参考百度百科后序遍历和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 1000struct 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;}
0 0
- (p138)非递归完成二叉树的遍历
- (p138)递归完成树的遍历
- 二叉树的递归,非递归遍历
- 二叉树的递归+非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的遍历--递归+非递归
- 二叉树的递归、非递归遍历
- 二叉树的递归非递归遍历
- (p138)只用固定量额外存储空间不用递归遍历二叉树
- 二叉树的先中后序遍历,递归遍历,非递归遍历
- 今天终于完成自己的第一个算法(非递归遍历二叉树)
- 利用非递归方法实现二叉树的后序遍历 .(待完成!!!!!!)
- 利用非递归方法实现二叉树的层次遍历 .(待完成!!!!!!)
- 二叉树的递归遍历与非递归遍历
- 二叉树的创建,递归遍历,非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的非递归遍历以及递归遍历
- 二叉树的非递归遍历&递归遍历
- AngularJS进阶(三十三)书海拾贝之简介AngularJS中使用factory和service的方法
- getenv/putenv/setenv/unsetenv
- starUML 2.5.1 for mac
- libcurl 静态编译及初步使用(Linux环境)
- x86平台 通过反汇编简单的从程序,分析理解计算机是如何工作的。
- (p138)非递归完成二叉树的遍历
- 1102. Invert a Binary Tree (25)
- 既能作为Application执行,又能作为Applet程序执行
- tcp三次握手和time wait --- 转
- 虚拟机下Linux系统root登陆
- python写一个爬虫(3)
- 【poj3984】迷宫问题——bfs/栈
- java 堆和栈的区别
- iOS学习笔记62- iOS开发小技巧之--WeakSelf宏的进化