sagelearnai

Path Sum II

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

Given a binary tree and targetSum, return all root-to-leaf paths whose node values sum to targetSum, each as a list of values. Order the paths from left to right, the order a DFS that visits left before right finds them.

Examples

text
root = [5,4,8,11,null,13,4,7,2,null,null,5,1], target = 22
→ [[5,4,11,2],[5,8,4,5]]
root = [1,2,3], target = 5  →  []

Hints

  1. This is Path Sum plus a path list: append on the way down, pop on the way back up (backtracking).
  2. When you record an answer, record a copy of the path, because the list keeps changing afterwards.

Approach

DFS keeps one shared path list:

text
dfs(node, rem):
  path.append(node.val); rem -= node.val
  if leaf and rem == 0: ans.append(copy(path))
  dfs(left, rem); dfs(right, rem)
  path.pop()                 # undo the choice

Sharing one list and popping on return is the core move of backtracking, and it avoids allocating a new list per node. The copies cost O(h) each, so the worst case is O(n·h).

Complexity

Time: O(n·h) including the copies. Space: O(h) besides the output.

Python solution
def pathSum(root, targetSum):
    ans, path = [], []
    def dfs(node, rem):
        if not node:
            return
        path.append(node.val)
        rem -= node.val
        if not node.left and not node.right and rem == 0:
            ans.append(path[:])
        dfs(node.left, rem)
        dfs(node.right, rem)
        path.pop()
    dfs(root, targetSum)
    return ans
JavaScript solution
function pathSum(root, targetSum) {
  const ans = [], path = [];
  const dfs = (node, rem) => {
    if (!node) return;
    path.push(node.val);
    rem -= node.val;
    if (!node.left && !node.right && rem === 0) ans.push([...path]);
    dfs(node.left, rem);
    dfs(node.right, rem);
    path.pop();
  };
  dfs(root, targetSum);
  return ans;
}