二叉树的非递归遍历(栈)
来源:互联网 发布:滇红 知乎 编辑:程序博客网 时间:2024/06/01 08:04
struct TreeNode{ int val; TreeNode *left,*right; TreeNode(int x):val(x),left(0),right(0){}};//前序遍历vector<int> preorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> s; TreeNode *p=root; while(!s.empty()||p) { while(p) { res.push_back(p->val); s.push(p); p=p->left; } if(!s.empty()) { p=s.top(); s.pop(); p=p->right; } } return res;}vector<int> preorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> s; TreeNode *p=root; while(!s.empty()||p) { if(p) { res.push_back(p->val); s.push(p); p=p->left; } else { p=s.top(); s.pop(); p=p->right; } } return res;}//中序遍历vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> s; TreeNode *p=root; while(!s.empty()||p) { while(p) { s.push(p); p=p->left; } if(!s.empty()) { p=s.top(); s.pop(); res.push_back(p->val); p=p->right; } } return res;}vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> s; TreeNode *p=root; while(!s.empty()||p) { if(p) { s.push(p); p=p->left; } else { p=s.top(); s.pop(); res.push_back(p->val); p=p->right; } } return res;}//后序遍历vector<int> postorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> s; TreeNode *cur=root,*prev=0; while(cur) { s.push(cur); cur=cur->left; } while(!s.empty()) { cur=s.top(); s.pop(); if(!cur->right||cur->right==prev) { res.push_back(cur->val); prev=cur; } else { s.push(cur); cur=cur->right; while(cur) { s.push(cur); cur=cur->left; } } } return res;}
http://blog.csdn.net/zhangxiangdavaid/article/details/37115355
0 0
- 二叉树的遍历(递归+非递归+层次遍历)
- 二叉树的遍历(非递归)
- 二叉树的遍历(非递归)
- 二叉树的遍历(非递归)
- 【树】二叉树的非递归遍历(栈&Morris)
- 二叉树的非递归遍历(使用栈)
- 二叉树的非递归遍历(栈)
- 用栈实现二叉树的遍历(非递归)
- 二叉树的递归,非递归遍历
- 二叉树的递归+非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的遍历--递归+非递归
- 二叉树的递归、非递归遍历
- 二叉树的递归非递归遍历
- 二叉树遍历(递归,非递归)
- 二叉树的遍历(递归实现+非递归实现)
- 二叉树的三种遍历(递归+非递归)
- 二叉树的遍历(递归与非递归)
- mysql 获取当前日期及格式化
- 在Linux/Mac下面删除所有的.svn文件
- Leetcode Copy List with Random Pointer 拷贝链表
- Android 之Activity启动模式(二)之 Intent的Flag属性
- 如何让DIV始终保持在屏幕中间
- 二叉树的非递归遍历(栈)
- Python 循环及函数range的用法
- can not be represented as java.sql.Timestamp
- callback site:blog.csdn.net/amazing_alex/article
- Altium Designer 使用sheetsymbol 绘制重复重复使用的模块
- CentOS利用iso镜像做本地yum源-make等命令无权限解决
- 苹果电脑MAC 在Finder里面显示隐藏文件方法
- Android HttpURLConnection使用
- Leetcode25: Longest Common Prefix