Skip to problem
←

Path Sum III

Medium 0 attempts

Given a binary tree root and an integer targetSum, return the number of nonempty downward paths whose node values sum to the target.

A path follows consecutive parent-to-child links. It may start at any node and end at any descendant, including the starting node itself. It cannot move upward, cross between sibling branches, or skip nodes. Different paths may overlap; count each choice of starting and ending nodes separately, even when their values are identical.

Return 0 for an empty tree. Negative and zero values are allowed. For a three-node chain of zeros and target 0, all six paths count: three single-node paths, two two-node paths, and the entire chain.

In the first example, the three paths summing to 8 are 5 → 3, 5 → 2 → 1, and -3 → 11.

Examples use level-order arrays with null for missing children. Your function receives nodes with val, left, and right properties.

Function contract

Implement pathSum(root, targetSum). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the number of nonempty downward paths with sum targetSum.

Example 1

Input
root = [10,5,-3,3,2,null,11,3,-2,null,1]
targetSum = 8
Output
3

Example 2

Input
root = [1]
targetSum = 1
Output
1
Constraints
  • 0 <= number of nodes <= 1000
  • -10^9 <= Node.val <= 10^9
  • -1000 <= targetSum <= 1000

Prefix Sum DFS

Track the frequencies of prefix sums along the current root-to-node route. Initialize the map with 0 → 1 to represent the empty prefix before the root.

If the sum through the current node is sum, a downward path ending here has the target sum whenever an earlier prefix equals sum - targetSum. Add that prefix's frequency, not just one: repeated prefix sums represent different starting points.

Count matches before inserting the current prefix, so a zero target does not count an empty path. Then visit both children. On returning, remove this node's prefix contribution; otherwise a later sibling could incorrectly match a prefix from a different branch. Delete entries whose frequency reaches zero so the map contains only active ancestors.

javascript
function pathSum(root, targetSum) {
  let count = 0;
  const prefixSums = new Map([[0, 1]]);
  function dfs(node, sum) {
    if (!node) return;
    sum += node.val;
    count += prefixSums.get(sum - targetSum) || 0;
    prefixSums.set(sum, (prefixSums.get(sum) || 0) + 1);
    dfs(node.left, sum);
    dfs(node.right, sum);
    const remaining = prefixSums.get(sum) - 1;
    if (remaining === 0) prefixSums.delete(sum);
    else prefixSums.set(sum, remaining);
  }
  dfs(root, 0);
  return count;
}

Time: O(n) expected | Space: O(h), where n is the number of nodes and h is tree height. Prefix sums remain exact JavaScript integers under the stated bounds.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript