sagelearnai

Path Sum III

Difficulty: Medium · Pattern: Trees & BST · LeetCode #437

Return the number of downward paths (from any node to any of its descendants, not necessarily root or leaf) whose values sum to targetSum.

Examples

text
root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8  →  3
   (5→3, 5→2→1, -3→11)
root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22  →  3

Hints

  1. A downward path is a contiguous slice of some root-to-node path. Does that remind you of an array problem?
  2. It is Subarray Sum Equals K: keep a map of prefix sums along the current root path.

Approach

Let cur be the sum from the root to the current node. A path ending here sums to target exactly when some ancestor's prefix equals cur - target. So:

text
count = {0: 1}                     # empty prefix
dfs(node, cur):
  cur += node.val
  ans += count[cur - target]
  count[cur] += 1
  dfs(left, cur); dfs(right, cur)
  count[cur] -= 1                  # backtrack: leave this path

The backtracking decrement is essential. Without it, prefix sums from a sibling branch (which are not ancestors) would be counted. Brute force (start a DFS from every node) is O(n²) on skewed trees. This is O(n).

Complexity

Time: O(n). Space: O(h) for the map's live entries plus recursion.

Python solution
from collections import defaultdict

def pathSum(root, targetSum):
    count = defaultdict(int)
    count[0] = 1
    ans = 0
    def dfs(node, cur):
        nonlocal ans
        if not node:
            return
        cur += node.val
        ans += count[cur - targetSum]
        count[cur] += 1
        dfs(node.left, cur)
        dfs(node.right, cur)
        count[cur] -= 1
    dfs(root, 0)
    return ans
JavaScript solution
function pathSum(root, targetSum) {
  const count = new Map([[0, 1]]);
  let ans = 0;
  const dfs = (node, cur) => {
    if (!node) return;
    cur += node.val;
    ans += count.get(cur - targetSum) || 0;
    count.set(cur, (count.get(cur) || 0) + 1);
    dfs(node.left, cur);
    dfs(node.right, cur);
    count.set(cur, count.get(cur) - 1);
  };
  dfs(root, 0);
  return ans;
}