LeetCode #145 Binary Tree Postorder Traversal

Program

Given a binary tree, return the postorder traversal of its nodes’ values.

Example

1
2
3
4
5
6
7
8
Input: [1,null,2,3]
1
\
2
/
3

Output: [3,2,1]

Solution1

Method: Depth-first Search (Recursive)

Time Complexity: O(n)

Space Complexity: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None


class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def helper(root, nodes):
if not root:
return
helper(root.left, nodes)
helper(root.right, nodes)
nodes.append(root.val)

ret = []
helper(root, ret)

return ret

Solution2

Method: Depth-first Search (Iterative)

Time Complexity: O(n)

Space Complexity: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []

stack = [(root, False)]
ret = []

while stack:
node, visited = stack.pop()

if node:
if not visited:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
else:
ret.append(node.val)

return ret