-
Notifications
You must be signed in to change notification settings - Fork 3
/
Path Sum
26 lines (23 loc) · 904 Bytes
/
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
# 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 hasPathSum(self, root, targetSum):
"""
:type root: Optional[TreeNode]
:type targetSum: int
:rtype: bool
"""
# If root is None, there is no path, return False
if not root:
return False
# Subtract the current node's value from targetSum
targetSum -= root.val
# Check if we have reached a leaf node and the targetSum is now 0
if not root.left and not root.right:
return targetSum == 0
# Recursively check the left and right subtrees
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)