二叉树的非递归遍历
来源:互联网 发布:我的世界 知乎 编辑:程序博客网 时间:2024/06/06 23:34
二叉树的非递归实现
在解决二叉树的问题的时候要善于把树划分成为根左子树和右子树
前序遍历:根–>左–>右
中序遍历:左–>根–>右
后序遍历:左–>右–>根
这三种遍历的方式的思想都是一样的,借助栈来保存,利用栈先进后出的特性
中序遍历也是同样的思想,而后序遍历大致也是同样的方式不过必须要做一个标记避免陷入死循环,因为只有右子树访问完了,才能将根节点访问并且pop出去,那么此时就需要加一个标记判断右子树是否访问完了,否则就会一直访问右子树,这样程序就会陷入死循环
#include<iostream>#include<stdlib.h>#include<stack>using namespace std;template<class T>struct BinaryTreeNode{ BinaryTreeNode( const T &x) :Lchild( NULL) ,Rchild( NULL) , value( x) , flag(0) { } T value; BinaryTreeNode<T > *Lchild; BinaryTreeNode<T > *Rchild; size_t flag;};template<class T>class BinaryTree{public: typedef BinaryTreeNode <T> Node; BinaryTree() { _root = NULL; } //构建一颗空树 BinaryTree( const T *arr, size_t size , T invalid) { size_t index = 0; _root = _CreatBinaryTree( arr, size , invalid, index); } void PrevOrder() { stack<Node *>s; Node*cur = _root; while (cur || !s.empty()) { while (cur) { cout << cur->value << " "; s.push(cur); cur = cur->Lchild; } Node*top = s.top(); s.pop(); cur = top->Rchild; } cout << endl; } void InOrder() { stack<Node *>s; Node*cur = _root; while (cur || !s.empty()) { while (cur) { s.push(cur); cur = cur->Lchild; } Node*top = s.top(); cout << top->value << " "; s.pop(); cur = top->Rchild; } cout << endl; } void PostOrder()//后序遍历 { stack<Node *>s; Node*cur = _root; while (cur || !s.empty()) { while (cur) { s.push(cur); cur = cur->Lchild; } Node*top = s.top(); if (top->Rchild == NULL ) { cout << top->value<< " "; top->flag = 1; s.pop(); } else { if (top->Rchild->flag != 1) { cur = top->Rchild; } else { cout << top->value << " "; s.pop(); } } } }protected: Node* _CreatBinaryTree(const T*arr, size_t size , T invalid, size_t &index ) { Node *root = NULL ; if (index < size&& arr[index ] != invalid) { root = new Node (arr[index]); root->Lchild = _CreatBinaryTree(arr , size, invalid, ++index); root->Rchild = _CreatBinaryTree(arr , size, invalid, ++index); } return root; }protected:Node * _root;};int main(){ int array1[10] = { 1, 2, 3, '#' , '#', 4, '#', '#' , 5, 6 }; BinaryTree<int >t1(array1,10,'#'); t1.PrevOrder(); t1.InOrder(); t1.PostOrder(); system( "pause"); return 0;}
0 0
- 二叉树的递归,非递归遍历
- 二叉树的递归+非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的遍历--递归+非递归
- 二叉树的递归、非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的先中后序遍历,递归遍历,非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的创建,递归遍历,非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的非递归遍历以及递归遍历
- 二叉树的非递归遍历&递归遍历
- 二叉树的递归遍历和非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历和非递归遍历
- 二叉树的构造,递归遍历,非递归遍历
- 二叉树的遍历(递归+非递归+层次遍历)
- 二叉树的递归遍历与非递归遍历
- 机器人走方格
- rails中的Preload, Eagerload, Includes and Joins
- jq-easyUI
- 抽象类(abstract class)和接口(interface)有什么异同
- spark数据分析之ip归属地查询
- 二叉树的非递归遍历
- expect脚本实例
- c++ tuple的操作
- Ubuntu下配置git
- 为Linux技术学习推荐看的书籍—《Linux就该这么学》
- save命令+get命令+start命令+edit命令+spool命令+临时变量+已定义的变量
- 如何将硬盘从一个虚拟机添加到另一个虚拟机
- Centos安装Sublime text 3
- Unable to connect to Command Metric Stream.解决方案