【LEETCODE】145-Binary Tree Postorder Traversal
来源:互联网 发布:直通车关键字优化 编辑:程序博客网 时间:2024/05/01 12:23
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?
参考:
http://bookshadow.com/weblog/2015/01/19/leetcode-binary-tree-postorder-traversal/
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] ans = [] #返回答案 stack = [root] #stack记录cur的轨迹 pre = None #pre跟随cur的脚步 while stack: cur = stack[-1] if pre is None or pre.left==cur or pre.right==cur: #当pre是cur的parent时,cur优先向左child走,没有左child再走右child if cur.left: stack.append(cur.left) elif cur.right: stack.append(cur.right) elif pre==cur.left and cur.right: #当pre是cur的左child时,并且cur有右child时,cur继续向右走 stack.append(cur.right) else: #当pre==cur时,或者pre==cur.left但是cur.right不存在时, ans.append(cur.val) #ans记录cur.val stack.pop() #stack向上跳一层 pre=cur <span style="font-family: Arial, Helvetica, sans-serif;"> #pre跟随cur的脚步</span> return ans
0 0
- LeetCode(145)Binary Tree Postorder Traversal
- LeetCode: Binary Tree Postorder Traversal [145]
- LeetCode 145 Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode || 145、Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode 145
- Leetcode[145]-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode(145):Binary Tree Postorder Traversal
- leetcode-145-Binary Tree Postorder Traversal
- [Leetcode 145, Hard] Binary Tree Postorder Traversal
- leetcode[145]:Binary Tree Postorder Traversal
- [leetcode-145]Binary Tree Postorder Traversal(c++)
- Leetcode #145 Binary Tree Postorder Traversal
- LeetCode 145 : Binary Tree Postorder Traversal
- LeetCode 145: Binary Tree Postorder Traversal
- 【LEETCODE】145-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- ubuntu12.04 更新源
- JS面向对象的几种创建方式:工厂模式、构造函数模式、原型模式、混合模式、动态原型模式
- GO语言学习:go语言实现android应用的步骤
- Sass入门-基本特性
- kernel mtd 分区与UBOOT 分区的理解
- 【LEETCODE】145-Binary Tree Postorder Traversal
- UIlbale 省略的枚举
- Android TextView显示中文不对齐问题
- 简介
- TinyOS03:Yeti插件的安装
- intellij idea tomcat jsp 热部署
- iOS 获取验证码倒计时
- CF #328
- 欢迎使用CSDN-markdown编辑器