二叉树前序、中序、后序非递归遍历
来源:互联网 发布:visio 数据流程图 编辑:程序博客网 时间:2024/04/28 06:27
#include <iostream>#include <stack>using namespace std;using std::stack;//链表节点template<class T>struct Node{ T data; Node<T> *left; Node<T> *right; Node<T>(T t) { left=NULL; right=NULL; data=t; }};//前序非递归template<class T>void preOrder(Node<T> *tree){ Node<T> *p=tree; stack<Node<T> *> stk; while(!stk.empty()||p) { if(p) { cout<<p->data<<endl; stk.push(p); p=p->left; } else { p=stk.top()->right; stk.pop(); } }}//中序非递归template<class T>void midOrder(Node<T> *tree){ Node<T> *p=tree; if(!p) return; stack<Node<T> *> stk; while(!stk.empty()||p) { while(p) { stk.push(p); p=p->left; } p=stk.top(); cout<<p->data<<endl; p=p->right; stk.pop(); }}//后序非递归template<class T>void lastOrder(Node<T> *tree){ Node<T> *p=tree; Node<T> *pre=p; if(!p) return; stack<Node<T> *> stk; while(!stk.empty()||p) { while(p) { stk.push(p); p=p->left; } p=stk.top(); if(p->right&&p->right!=pre) { p=p->right; } else { cout<<p->data<<endl; pre=p; stk.pop(); p=NULL; } }}//后序非递归方案2,先按照根节点-右节点-左节点的顺序访问,然后reversetemplate<class T>void lastOrder(Node<T> *tree){Node<T> *p=tree;stack<Node<T> *> stk;vector<T> vec;while(p||!stk.empty()){ if(p) { vec.push_back(p->data); stk.push(p); p=p->right; } else { p=stk.top()->left; stk.pop(); }}reverse(vec.begin(),vec.end());for(auto e:vec) cout<<e<<" ";return 0;}//testint main(int argc, char* argv[]){ Node<int> *tree=new Node<int>(1); Node<int> *p=tree; p->left=new Node<int>(2); p->right=new Node<int>(3); p=p->left; p->left=new Node<int>(4); p->right=new Node<int>(5); p=p->right; p->right=new Node<int>(6); p->left=new Node<int>(7); lastOrder(tree); return 0;}
0 0
- 二叉树前序,中序,后序非递归遍历
- 二叉树前序、中序、后序非递归遍历
- 二叉树前序、中序、后序非递归遍历
- 二叉树前序、中序和后序非递归遍历的方法
- 二叉树前序遍历,中序遍历非递归版本
- 二叉树前序遍历和中序遍历 非递归算法
- 4. 二叉树前序、中序、后序递归遍历算法,二叉树前序非递归遍历算法
- 二叉树的前序、中序、后序非递归遍历
- 二叉树的中序,前序,后序非递归遍历
- 二叉树前序,中序,后序遍历(递归)
- 二叉树前序、中序、后序遍历非递归写法
- 二叉树前序、中序、后序遍历非递归写法
- 二叉树前序、中序、后续遍历(递归实现)
- 二叉树前序、中序、后序三种遍历的非递归算法
- 递归中序遍历二叉树
- 用递归中序遍历二叉树
- 【二叉树遍历】中序------非递归
- 非递归中序遍历二叉树
- leetcode 题解 || Valid Sudoku 问题
- 入职第一天。安装Yii1.1
- NSSetUncaughtExceptionHandler
- 禁止ViewPager左右滑动
- java.lang.Object.clone()分析
- 二叉树前序、中序、后序非递归遍历
- C/C++工程师综合练习卷
- java第八章集合中的IdentityHashMap的用法
- C++基础
- DIV+CSS布局-固定页面开度布局
- Spring+CXF开发WebService
- F5刷新你所不知道的知识
- Lucene连接数据库进行全文搜索初探(一)
- 虚函数和纯虚函数的区别