SDE & MLE Prep

112. Path Sum

Problem

Decide whether the binary tree has a root-to-leaf path whose node values add up to targetSum.

Example: [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 → true (5 → 4 → 11 → 2)

Subtract node values on the way down; at a leaf, check the remainder equals the leaf value.

Complexity: O(n).

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right:
            return root.val == targetSum
        rest = targetSum - root.val
        return self.hasPathSum(root.left, rest) or self.hasPathSum(root.right, rest)