InterviewPrepKit

Home / Coding / Trees

Path Sum

easy Original β†—
Solving tips
  • Carry the remaining target DOWN the recursion: subtract each node's value as you descend, so you never need to store the whole path. O(n) time, O(h) space.
  • Success is landing on a LEAF (no children) with remaining == node.val; combine results up with 'or'.
  • Pitfall: the empty tree with target 0 must return False β€” there is no path; don't check remaining == 0 at a null node (that also wrongly accepts non-leaf stops).
  • Pitfall: values can be negative, so don't prune on remaining < 0 β€” a path can dip below and recover; the leaf check must fire only at true leaves.

Problem

You are given the root of a binary tree and an integer targetSum. Determine whether the tree contains at least one root-to-leaf path whose node values add up exactly to targetSum. Return True if such a path exists, otherwise False.

A leaf is a node with no children. The path must start at the root and end at a leaf β€” it cannot stop partway down.

Examples

Example 1

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: True

The path 5 β†’ 4 β†’ 11 β†’ 2 sums to 22.

Example 2

Input: root = [1,2,3], targetSum = 5
Output: False

The two root-to-leaf paths sum to 1+2=3 and 1+3=4; neither is 5.

Example 3

Input: root = [], targetSum = 0
Output: False

An empty tree has no root-to-leaf paths at all, so the answer is False even for target 0.

Constraints

  • The number of nodes is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

Node values can be negative, so you cannot prune a branch just because the running sum already exceeds the target.

Think about it first

Hint 1 As you walk down from the root, what single number do you need to carry with you to know whether the current path can still succeed?
Hint 2 Instead of adding values up, try subtracting: at each node, reduce the remaining target by the node's value. What must be true when you land on a leaf?
Hint 3 Recurse: `hasPathSum(node, t)` is true if `node` is a leaf and `node.val == t`, or if either subtree has a path summing to `t - node.val`. The empty tree is `False`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.