LeetCode #257 Binary Tree Paths

Problem

Given a binary tree, return all root-to-leaf paths.

Example

1
2
3
4
5
6
7
8
9
10
11
Input:

1
/ \
2 3
\
5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

Solution

Method: Depth-first Search

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

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

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

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

if node:
val = str(node.val)
if not node.left and not node.right:
complete_path = path + [val]
ret.append('->'.join(complete_path))
else:
if node.left:
stack.append((node.left, path + [val]))
if node.right:
stack.append((node.right, path + [val]))

return ret