-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112_Path_Sum.py
More file actions
26 lines (20 loc) · 824 Bytes
/
Copy path112_Path_Sum.py
File metadata and controls
26 lines (20 loc) · 824 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
26
# 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:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
return self.dfs(root, targetSum, 0)
def dfs(self, root: Optional[TreeNode], targetSum: int, currentSum: int) -> bool:
if root == None:
return False
if root.left == None and root.right == None:
if currentSum + root.val == targetSum:
return True
if self.dfs(root.left, targetSum, currentSum + root.val):
return True
if self.dfs(root.right, targetSum, currentSum + root.val):
return True
return False