LeetCode 145. Binary Tree Postorder Traversal
2016-04-14 20:43
316 查看
先自己在纸上画棵树,发现可以用stack实现迭代版的后序遍历,最开始先把root压入栈。另外维护一个栈,记录对应节点出栈的次数,如果是1,表明左右节点已输出,就输出;如果为0,说明左右节点还未压入栈,就把次数加1,且把左右节点压入栈。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if(!root) return res; stack<TreeNode*> stk; stack<int> time; stk.push(root); time.push(0); while(!stk.empty()){ TreeNode* top = stk.top(); int tmp = time.top(); if(tmp == 0){ ++tmp; time.pop(); time.push(tmp); if(top->right) {stk.push(top->right);time.push(0);} if(top->left) {stk.push(top->left);time.push(0);} } else{ res.push_back(top->val); stk.pop();time.pop(); } } return res; } };
相关文章推荐
- 走向视网膜(Retina)的Web时代
- 复利计算升级
- LeetCode - Binary Tree Level Order Traversal
- Android实现图片压缩并且不失真
- 谷歌发布联机版人工智能系统 TensorFlow
- HDU 5247 找连续数(暴力)
- epoll网络编程实例
- C++标准库和标准模板库
- 第三周项目4-辨数字
- 在VS中向命令行添加参数的方法
- 创建和导出SVG的技巧(转载)
- ubuntu上用python安装扩展包遇到的一些问题
- UIImageView圆角,自适应图片宽高比例,图片拉伸,缩放比例和图片缩微图
- ListView这样用
- 软考中高项学员:2016年4月11日作业
- 2016/4/14
- Autofac创建实例的方法总结
- 【LeetCode】98. Validate Binary Search Tree 解法,中序遍历,搜索二叉树合法性
- Redis的spring整合(六)
- 有趣的积水问题(Twitter编程面试题)