-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path084-path-sum.py
More file actions
52 lines (39 loc) · 1.42 KB
/
084-path-sum.py
File metadata and controls
52 lines (39 loc) · 1.42 KB
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
48
49
50
51
52
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_left(self, value):
self.left = TreeNode(value)
return self.left
def insert_right(self, value):
self.right = TreeNode(value)
return self.right
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def recurse(node: TreeNode, running_sum: int):
if not node:
return
running_sum += node.val
sum_found = recurse(node.left, running_sum)
if sum_found:
return True
sum_found = recurse(node.right, running_sum)
if sum_found:
return True
if not node.left and not node.right and running_sum == sum:
return True
return False
# We use a local variable for the running_sum so when the recursion is back up,
# it value is restored to what it was before the calls were made. It avoid substracting
# when going back up the stack.
# Also, we shortcut the recursion if we found the sum.
return recurse(root, 0)
tree = TreeNode(50)
left = tree.insert_left(30)
right = tree.insert_right(70)
ll = left.insert_left(10)
lr = left.insert_right(40)
rl = lr.insert_left(60)
rr = lr.insert_right(80)
print(Solution().hasPathSum(tree, 90))