Binary Tree Postorder Traversal
Description:
Given a binary tree, return the postorder traversal of its nodes’ values.
Example
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Challenge
Can you do it without recursion?
Code:
1. 递归
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# write your code here
if not root:
return []
return self.postorderTraversal(root.left)+self.postorderTraversal(root.right)+[root.val]
2. 非递归
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# write your code here
res = []
if not root:
return res
stack = [root]
cur = root
while stack:
if cur.left:
stack.append(cur)
cur = cur.left
stack[-1].left = None
elif cur.right:
stack.append(cur)
cur = cur.right
stack[-1].right = None
else:
res.append(cur.val)
cur = stack.pop()
return res