二叉树的遍历
来源:互联网 发布:腾讯大数据 会 11.22 编辑:程序博客网 时间:2024/06/09 16:37
假设有一颗这样的二叉树,该结构如图:
中序遍历:其遍历顺序为左——根——右,其上面二叉树的中序遍历的输出结果为:A/B*C*D+E,整个遍历过程函数调用了19次。
前序遍历:其遍历顺序为根——左——右,其上面二叉树的前序遍历的输出结果为:+/ABCDE,整个遍历过程函数也被调用了19次。**
后序遍历:其遍历顺序为左——右——根,其上面二叉树的后序遍历的输出结果为:AB/C*D*E+,整个遍历过程函数也被调用了19次。
上面三种遍历都是按照递归的方式遍历,其实我们可以用栈数据结构模拟上面的三种遍历模式,就拿中序遍历来说,其相当于左结点一直在进栈,直到遇到空结点,然后再把其栈顶的结点弹出栈,再让遍历其右儿子。
层序遍历:其遍历顺序为自上而下,自左而右地遍历每一层的结点,其上面二叉树的层次遍历输出结果:+*E*D/CAB,可以用一个队列来保存其遍历顺序,首先根结点入队,然后再其左结点入队,再其右结点入队,让后弹出对头的元素,再继续重复前面的操作,直到队列为空。
代码实现:
#include <iostream>#include<stdio.h>#include<stack>#include<queue>using namespace std;typedef struct node *tree_pointer;struct node{ int data; tree_pointer left_child,right_child;};//中序遍历void inorder(tree_pointer ptr){ if(ptr) { inorder(ptr->left_child); printf("%d",ptr->data); inorder(ptr->right_child); }}//前序遍历void preorder(tree_pointer ptr){ if(ptr) { printf("%d",ptr->data); inorder(ptr->left_child); inorder(ptr->right_child); }}//后序遍历void postorder(tree_pointer ptr){ if(ptr) { inorder(ptr->left_child); inorder(ptr->right_child); printf("%d",ptr->data); }}//中序迭代遍历void iter_inorder(tree_pointer node){ stack<tree_pointer> tree; for(;;) { //该节点的所有左结点进栈 for(;node;node=node->left_child) tree.push(node); node=tree.top(); //删除栈顶元素 tree.pop(); if(!node) break; printf("%d",node->data); //遍历树的右儿子 node=node->right_child; }}//二叉树层次遍历void level_order(tree_pointer ptr){ queue<tree_pointer> tree; if(!ptr) return; tree.push(ptr); for(;;) { ptr=tree.front(); //删除队头元素 tree.pop(); if(ptr) { printf("%d",ptr->data); //左结点入队 if(ptr->left_child) tree.push(ptr->left_child); //右结点入队 if(ptr->right_child) tree.push(ptr->right_child); } else break; }}
0 0
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 在github上查找优秀开源库的方法
- Java加密与解密的艺术-Base64
- c++----------------volatile
- 获得客户端真实ip地址
- 在Google被封的那些日子裏,我們這樣科學上網
- 二叉树的遍历
- 线性表(3)--习题
- HDU 1385 Minimum Transport Cost(folyd+记录路径)
- 同学会
- [Java Web]ibatis使用queryForMap实现数据查找等操作
- [Win32] Windows Sockets 2笔记(3)TCP Server端的实现(长数据接收+超时机制)
- Android存储使用参考
- Maven错误信息:Missing artifact jdk.tools:jdk.tools:jar:1.6
- 界面编辑神器--Bootstrap