Path Sum
Difficulty: Easy · Pattern: Trees & BST · LeetCode #112
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path whose values add up to targetSum. A leaf is a node with no children.
Examples
text
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 → true (5→4→11→2)
root = [1,2,3], targetSum = 5 → false
root = [], targetSum = 0 → false (no paths at all)Hints
- Pass the remaining sum down the recursion.
- Only check the sum at a leaf. A node with a single child is not the end of a path.
Approach
Recurse with remaining = targetSum - node.val. At a leaf, return remaining == 0. Otherwise return left || right.
A common bug is returning true at a null child when remaining == 0. In [1,2] with target 1, the root has a null right child, but 1 alone is not a root-to-leaf path because the root isn't a leaf. Checking only at real leaves avoids this.
Complexity
Time: O(n). Space: O(h).
Python solution
def hasPathSum(root, targetSum):
if not root:
return False
rem = targetSum - root.val
if not root.left and not root.right:
return rem == 0
return hasPathSum(root.left, rem) or hasPathSum(root.right, rem)JavaScript solution
function hasPathSum(root, targetSum) {
if (!root) return false;
const rem = targetSum - root.val;
if (!root.left && !root.right) return rem === 0;
return hasPathSum(root.left, rem) || hasPathSum(root.right, rem);
}