程序3——二叉树的前中后层序遍历
来源:互联网 发布:5x兴趣社区淘宝商店 编辑:程序博客网 时间:2024/06/06 12:35
定义数据结构
typedef struct BiTree { int data; struct BiTree *lchild, *rchild;} BiTree;
前序遍历
void PreOder(BiTree *T) { if( T == null ) { return; } stack s; BiTree *t = T; while( t != null || !s.isEmpty() ) { if (t != null) { print(t->data); s.push(t); t = t->lchild; } else { t = s.pop(); t = t->rchild; } }}
中序遍历
中序遍历的非递归与前序的差不多,再写一下,熟练熟练。
void inOder(BiTree *T) { if ( T == null ) { return; } stack s; BiTree *t = T; while ( t != null || !s.isEmpty() ) { if (t != null) { s.push(t); t = t->lchild; } else { t = s.pop(); print(t->data); t = t->rchild; } }}
后序遍历
后序遍历相对于前两种来说,要复杂一些。要么使用两个栈,要么就要一些稍复杂、晦涩的逻辑。
void postOrder(BiTree *T) { if (T == null) { return; } stack s, out; BiTree *t = T; s.push(t); while( !s.isEmpty() ) { t = s.pop();; out.push(t); if (t->lchild != null) { s.push(t->lchild); } if (t->rchild != null) { s.push(t->rchild); } } while( !out.isEmpty() ) { t = out.pop(); print(t->data); }}
使用两个栈,逻辑比较简单,但是却多用了一点点内存,下面的代码只使用一个栈实现。
void postOrder(BiTree *T) { if ( T == null ) { return; } stack s; BiTree *t = T; BiTree *pre = null; while ( t != null || !s.isEmpty() ) { if (t != null) { s.push(t); t = t->lchild; } else if ( s.top()->rchild == pre) { pre = s.pop(); print(pre->data); } else { t = s.top()->rchild; pre = null; } }}
这种实现比较难搞懂的就是这个pre,这个pre记录着上次访问过(打印出)的节点,程序刚开始执行时,自然pre=null。当栈顶元素的rchild等于pre,说明栈顶元素的rchild已经访问完了,栈顶元素就可以出栈了;如果不等于pre,则需要访问其rchild。不要忘了,二叉树的定义就是一个递归定义,左右子树都是二叉树。这样可以将,s.top()->rchild看成是T,重新执行。
层序遍历
层序遍历使用就不是栈了,而是队列
void levelOrder(BiTree *T) { if ( T == null ) { return; } queue q; BiTree *t = T; q.enQueue(t); while (!q.isEmpty()) { t = q.deQueue(); print(t->data); if (t->lchild) q.enQueue(t->lchild); if (t->rchild) q.enQueue(t->rchild); }}
层序遍历比较简单,下面对其变化一下。要求:逐层打印节点。
这时需要记录孩子节点的个数。
void levelOrder(BiTree *T) { if (T == null) { return; } BiTree *t = T; queue q; int curCount = 1; int nextCount = 0; q.enQueue(t); while (!q.isEmpty()) { t = q.deQueue(); print(t->data); curCount--; if(t->lchild) { q.enQueue(t->lchild); nextCount++; } if(t->rchild) { q.enQueue(t->rchild); nextCount++; } if(curCount == 0) { print("\n"); curCount = nextCount; nextCount = 0; } }}
0 0
- 程序3——二叉树的前中后层序遍历
- 小程序(3)——二叉树遍历的非递归实现(三种遍历顺序)
- 数据结构——树(3):二叉树的前中后层序遍历,Morris遍历比较试验
- 二叉树遍历的递归算法程序
- 二叉树的基本遍历程序
- 二叉树的应用—二叉树遍历的应用
- 数据结构——二叉树的遍历
- 数据结构——二叉树的遍历
- 数据结构——二叉树的遍历
- 数据结构——二叉树的遍历
- 数据结构——二叉树的遍历
- 数据结构——二叉树的遍历
- 英伟达在线程序测评——后续遍历二叉树的序列转前序输出
- LeetCode—二叉树遍历的情况
- LeetCode—二叉树的遍历
- 二叉树的遍历之——Morris遍历
- 二叉树——二叉树的遍历
- 二叉树——二叉树的遍历
- js:有关TypeError: invalid 'in' operand obj的错误
- 福昕阅读器快速删除书签的方法
- Hadoop学习笔记(二)浅谈Hadoop守护进程
- Mybatis简单入门<学习随笔>
- SecureCRT配置
- 程序3——二叉树的前中后层序遍历
- 根据文件相对路径获得文件的绝对路径(windows)
- 被忽略却很有用的html标签
- java 集合类
- 关于使用Python3进行网络爬虫的字符问题
- Vim技巧
- 《计算机操作系统》总结三(内存管理)
- 汽车年检,备忘一下,估计2年以后才有用了
- Android studio 安装 环境搭建