LeetCode 145 Binary Tree Postorder Traversal(二叉树后序遍历)
来源:互联网 发布:恶灵附身优化怎么样 编辑:程序博客网 时间:2024/05/21 08:42
Given 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?
题目大意:写出二叉树非递归后序遍历的方法。
解题思路:对于任意节点N:
1. 将N入栈
2. 如果N没有左孩子和右孩子,或者N存在左孩子或右孩子但都已经被访问过了,那么可以直接访问N
3. 如果N存在左孩子或右孩子且还没被访问过,那么将N的右孩子和左孩子依次入栈,然后将栈顶元素置为N,重复步骤2和3
4. 直到N为空且栈为空,遍历结束
参考资料:http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
代码如下:
/** * 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) { if(root == nullptr) return vector<int>(); vector<int> ans; stack<TreeNode*> stk; TreeNode* cur; TreeNode* pre = nullptr; stk.push(root); while(stk.size()){ cur = stk.top(); if((cur->left == nullptr && cur->right == nullptr) || (pre && (pre == cur->left || pre == cur->right))){ ans.push_back(cur->val); stk.pop(); pre = cur; }else{ if(cur->right) stk.push(cur->right); if(cur->left) stk.push(cur->left); } } return ans; }};
阅读全文
0 0
- LeetCode 145 Binary Tree Postorder Traversal(二叉树后序遍历)
- Leetcode: Binary Tree Postorder Traversal(二叉树后序遍历)
- LeetCode 145. Binary Tree Postorder Traversal(二叉树后序遍历)
- Leetcode Binary Tree Postorder Traversal 二叉树后序遍历
- 145.leetcode Binary Tree Postorder Traversal(easy)[二叉树后序遍历]
- [leetcode-二叉树后序遍历]--145. Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal (二叉树后序遍历)
- 【leetcode】145Binary Tree Postorder Traversal(二叉树非递归后序遍历)
- LeetCode 145:Binary Tree Postorder Traversal(后序遍历)
- Binary Tree Postorder Traversal 二叉树后续遍历@LeetCode
- [leetcode]Binary Tree Postorder Traversal 二叉树后序非递归遍历
- leetcode 145. Binary Tree Postorder Traversal 二叉树后续遍历
- LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)
- Binary Tree Postorder Traversal 非递归实现二叉树后序遍历
- LeetCode145——Binary Tree Postorder Traversal二叉树后序遍历
- 二叉树后序遍历——145. Binary Tree Postorder Traversal
- binary-tree-postorder-traversal(后序遍历二叉树)
- LeetCode Binary Tree Postorder Traversal 二叉树后序遍历 递归和非递归解法
- oracle中序列详解(转)
- 欢迎使用CSDN-markdown编辑器
- Mybatis获取插入记录的自增长ID
- 《Using OpenRefine》翻译~13
- Win7摄像头驱动错误怎么办?Win7摄像头驱动错误的解决方法
- LeetCode 145 Binary Tree Postorder Traversal(二叉树后序遍历)
- JavaScript
- codeforces 770B Maximize Sum of Digits
- pom.xml添加spring依赖,统一管理版本
- MVC Controller向View传值(ViewData与ViewBag)
- C# 序列化与反序列化
- 千万别把qq截图直接复制到csdn,写完后会不见的!
- Eclipse常用快捷键
- Kotlin概述与Java的比较