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?
Python Solution 1:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def postorder(root):
if not root: return
postorder(root.left)
postorder(root.right)
res.append(root.val)
postorder(root)
return res
Python Solution 2:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
stack = [root]
res = []
while stack:
node = stack[-1]
if node.left:
stack.append(node.left)
node.left = None
continue
if node.right:
stack.append(node.right)
node.right = None
continue
stack.pop()
res.append(node.val)
return res
Summary:
- nothing to say
LeetCode: 145. Binary Tree Postorder Traversal
近期评论