Problem 455618 · medium · Level 04 Non-Linear Data Structures

All Root-to-Leaf Paths With a Target Sum

binary tree · backtracking · recursion

Given the root of a binary tree and an integer target, return all root-to-leaf paths whose values add up to target. Each path is a list of node values from the root down to the leaf. Paths may be returned in any order. Return [] if no path qualifies.

Examples

         6
       /   \
      3     -2
     / \    / \
    4   1  9   5
       / \      \
      7   2      1

Input:  root = build_tree([6, 3, -2, 4, 1, 9, 5, None, None, 7, 2, None, None, None, 1]), target = 13
Output: [[6, 3, 4], [6, -2, 9]]

Input:  root = build_tree([4, 9, -1]), target = 12
Output: []

Input:  root = build_tree([2, 3, 5, None, None, None, 1]), target = 7
Output: []
Explanation: 2 -> 5 adds up to 7, but 5 is not a leaf; the full path 2 -> 5 -> 1 adds up to 8.

Constraints

  • 0 <= number of nodes <= 1000
  • -1000 <= node.val, target <= 1000

Goals

  • Track the remaining sum while descending
  • Copy a path when it is recorded so later backtracking does not change it
Starting Python…