902. Path Sum II — All Root-to-Leaf Paths

MediumTreesBinary TreeDFSBacktracking

Given the root of a binary tree and a target sum, return all root-to-leaf paths whose node values add up to exactly the target, each path as a list of values from root to leaf. Return the paths as a nested array in left-to-right order. The input gives a level-order tree array and the target separated by ' | '.

Input: A level-order tree array and the target, separated by ' | '.

Output: Nested array — each qualifying root-to-leaf path.

Examples

Example 1
Input: [5,4,8,11,null,13,4,7,2,null,null,5,1] | 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: Two paths sum to 22.
Example 2
Input: [1,2,3] | 4
Output: [[1,3]]
Explanation: One qualifying path.
Example 3
Input: [1,2,3] | 9
Output: []
Explanation: No path sums to 9.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →