binary-tree
depth-first-search
backtracking

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's node values sum to targetSum.

A leaf is a node with no children. Each returned path should list node values from root to leaf, in order.

Input / output

  • Input: root: TreeNode, targetSum: int (JSON test fixture for root is a LeetCode-style level-order array, e.g. [5,4,8,11,null,13,4,7,2,null,null,5,1], with null for a missing child)
  • Output: int[][], one row per matching path, each row root-to-leaf in order (rows may appear in any order that matches a valid DFS traversal order)

Constraints

  • 0 <= number of nodes <= 5,000
  • -1,000 <= node value <= 1,000
  • -1,000 <= targetSum <= 1,000

Follow-up

How would you adapt this to return the paths as soon as a match is found, without holding the full result set in memory at once?

Examples

Example 1

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

Example 2 (no matching path)

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

Example 3 (empty tree)

Input: root = [], targetSum = 0
Output: []
🔒 6 hidden

Running will execute all 9 cases, including 6 hidden ones.