MediumBacktrackingTreeDepth-First SearchBinary Tree

1 approach, code in every language

Problem description

You are given the root of a binary tree together with an integer targetSum. A root-to-leaf path is a sequence of nodes that begins at the root and ends at a leaf, moving only from a parent to one of its children.

Return every root-to-leaf path whose node values add up exactly to targetSum. Each qualifying path should be returned as the list of node values encountered along the way, and the paths themselves may be returned in any order.

A leaf is a node that has no children. If no path reaches the target, return an empty list.

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]]

Two root-to-leaf paths sum to 22: 5 -> 4 -> 11 -> 2 and 5 -> 8 -> 4 -> 5.

Example 2

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

Output: []

The root-to-leaf paths sum to 3 (1 -> 2) and 4 (1 -> 3); neither reaches 5.

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

After the pattern

Now solve one you haven't seen.

Ridge Descents Matching a Drop is our own problem on the technique behind Path Sum II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free