[Leetcode]Binary Tree Postorder Traversal
来源:互联网 发布:java 查询条件封装 编辑:程序博客网 时间:2024/06/05 17:54
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?
树的后序遍历~同样,先是递归解法~代码如下~
class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): if root is None: return [] self.res = [] self.helper(root) return self.res def helper(self, root): if root is None: return self.helper(root.left) self.helper(root.right) self.res.append(root.val)
非递归解法如下~
1)如果当前栈顶元素的右结点存在并且还没访问过(也就是右结点不等于上一个访问结点),那么就把当前结点移到右结点继续循环;
2)如果栈顶元素右结点是空或者已经访问过,那么说明栈顶元素的左右子树都访问完毕,应该访问自己继续回溯了。
class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): if root is None: return [] res, stack, curr, prev = [], [], root, None while stack or curr: if curr: stack.append(curr) curr = curr.left else: parent = stack[-1] if parent.right in (None, prev): prev = stack.pop() res.append(prev.val) else: curr = parent.right return res
还有Morris遍历法,可以参考这篇博文 http://blog.csdn.net/linhuanmars/article/details/22009351
0 0
- 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
- 【LeetCode】Binary Tree Postorder Traversal
- Android中自定义ViewGroup
- pcap文件解析--pcap文件头与包文件头(一)
- 2015/01/16
- 深入理解Linux内核-内核同步
- OpenCV2.4.4中调用SIFT特征检测器进行图像匹配
- [Leetcode]Binary Tree Postorder Traversal
- 搬水果--超时
- pcap文件解析(二)--初识IP包
- 三大框架面试笔记-Hibernate
- 【OpenCV】SIFT原理与源码分析
- jquery 添加标签不响应click事件
- unity之血条
- 2015年,怎么过?
- RTOS一般锁保护使用与解决死锁问题