[LeetCode] Binary Tree Postorder Traversal [42]
来源:互联网 发布:非凡软件站 编辑:程序博客网 时间:2024/04/29 08:45
题目
Binary Tree Postorder Traversal
Total Accepted: 23797 Total Submissions: 76975My SubmissionsGiven a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
解题思路
于中序遍历类似,使用stack。不过此题注意需要使用一个额外的指针来保证其左右孩子都已经被访问过。
实现代码
vector<int> postorderTraversal(TreeNode *root) { vector<int> ret; if (root == NULL) return ret; TreeNode *pNode = NULL; TreeNode *pLast = NULL; std::stack<TreeNode *> s; s.push(root); while (!s.empty()) { pNode = s.top(); if ( (pNode->left == NULL && pNode->right == NULL) || ((pLast!=NULL)&& (pNode->left == pLast || pNode->right == pLast))) { ret.push_back(pNode->val); pLast = pNode; s.pop(); } else { if (pNode->right != NULL) s.push(pNode->right); if (pNode->left != NULL) s.push(pNode->left); } } return ret; }
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/38323117 )
0 0
- [LeetCode] Binary Tree Postorder Traversal [42]
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- leetcode Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- LeetCode | Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 中国剩余定理
- Android adb devices显示no permission
- 自定义模型SearchModel ------ Model-View-Control(MVC)架构(8)
- VMware虚拟化培训手册
- 杭电2045不容易系列之(3)—— LELE的RPG难题(递推涂颜色)----20140731
- [LeetCode] Binary Tree Postorder Traversal [42]
- OpenCV学习笔记【6】:从摄像机读入数据
- JavaScript提高:003:easy UI实现tab页面自适应问题
- 使用数组初始化vector
- POJ【2001】Shortest Prefixes----字典树
- 蔫奇撑羞铆继躺洲量贷新匹癸
- 局域网共享问题全方位解决
- POJ 1276 Cash Machine (DP)
- 简单2D飞行游戏练习