Data Structures19 sections · 729 units
Open in Course

Path Sum Solution

Subtract as you descend

Subtract the current value and recurse:

function 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: O(n)O(n). Space: O(h)O(h).