LeetCode #144 Binary Tree Preorder Traversal

Problem

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

Example

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

Output: [1,2,3]

Boundary Conditions

  • Will input list node be null?

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

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

ret.append(root.val)
self.preorderTraversal(root.left, ret)
self.preorderTraversal(root.right, ret)

return ret

or

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

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

ret = []
stack = [root]

while stack:
node = stack.pop()
if node:
ret.append(node.val)
stack.append(node.right)
stack.append(node.left)

return ret