-
Notifications
You must be signed in to change notification settings - Fork 0
/
257_Binary_Tree_Paths.py
47 lines (41 loc) · 1.47 KB
/
257_Binary_Tree_Paths.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
# 2 Possible Solutions
# 1. Recursion
# 2. Iteration
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# Recursion
# Time: O(N), Space: O(log N)/N
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def construct_paths(root, path):
if root:
path += str(root.val)
if not root.left and not root.right: # if reach a leaf
paths.append(path) # update paths
else:
path += '->' # extend the current path
construct_paths(root.left, path)
construct_paths(root.right, path)
paths = []
construct_paths(root, '')
return paths
# Iteration
# Time: O(N), Space: O(log N)/N
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root:
return []
paths = []
stack = [(root, str(root.val))]
while stack:
node, path = stack.pop()
if not node.left and not node.right:
paths.append(path)
if node.left:
stack.append((node.left, path + "->" + str(node.left.val)))
if node.right:
stack.append((node.right, path + "->" + str(node.right.val)))
return paths