Subtract the current value and recurse:
def hasPathSum(root, targetSum):
if root == null:
return false
targetSum -= root.val
if root.left == null and root.right == null:
return targetSum == 0
return (hasPathSum(root.left, targetSum) or
hasPathSum(root.right, targetSum))
The subtraction happens before the leaf check. At a leaf, if the remaining sum is 0, you found a valid path.
Common bug: returning true when hitting null. Null is not a leaf—it means "no node here." Only count actual leaves (nodes with no children).
Time: . Space: .