-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path257-binary_tree_paths.py
34 lines (29 loc) · 1.04 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
"""
https://leetcode.com/problems/binary-tree-paths/submissions/
Recursive DFS
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
paths = []
def traverse(node, path_so_far):
# base case: if leaf (add the path to paths)
if not node.left and not node.right:
paths.append(path_so_far)
# recursive case: update the path_so_far & recurse
else:
if node.left:
traverse(node.left, "{}->{}".format(path_so_far, node.left.val))
if node.right:
traverse(node.right, "{}->{}".format(path_so_far, node.right.val))
traverse(root, str(root.val))
return paths