-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0112-path-sum.py
More file actions
25 lines (24 loc) · 798 Bytes
/
0112-path-sum.py
File metadata and controls
25 lines (24 loc) · 798 Bytes
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
# Recursive Solution
class Solution:
def hasPathSum(self, root, sum):
if not root:
return False
sum -= root.val
if not root.left and not root.right:
return sum == 0
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
# Iterative Solution
class Solution:
def hasPathSum(self, root, sum):
de = [
(root, sum - root.val),
]
while de:
node, curr_sum = de.pop()
if not node.left and not node.right and curr_sum == 0:
return True
if node.right:
de.append((node.right, curr_sum - node.right.val))
if node.left:
de.append((node.left, curr_sum - node.left.val))
return False