-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path112_path_sum
50 lines (40 loc) · 1.31 KB
/
112_path_sum
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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# BFS
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
toCheck = {root}
while toCheck:
temp = set()
for x in toCheck:
if x.val == sum and not x.left and not x.right: return True
if x.left:
x.left.val = x.left.val + x.val
temp.add(x.left)
if x.right:
x.right.val = x.right.val + x.val
temp.add(x.right)
toCheck = temp
return False
#DFS
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
if not root.left and not root.right and root.val == sum:
return True
sum -= root.val
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)