List Every Root-to-Leaf Route With a Given Total
Implement routesWithTotal
You are given the root of a binary tree and an integer target. A route starts at the root, moves downward, and ends at a leaf (a node with no children). Return every route whose node values add up to exactly target, each written as the list of values from the root to the leaf. Routes are listed in left-to-right order of their leaves; if no route works, return an empty list.
You can collect all routes and filter them afterwards, or keep a running "remaining amount" while you walk so that only routes that succeed are ever copied.
Example 1:
Input: root = [8,4,6,5,3,1,9], target = 15
Output: [[8,4,3],[8,6,1]]
Example 2:
Input: root = [1,2,3], target = 4
Output: [[1,3]]
Example 3:
Input: root = [], target = 0
Output: []
+ 12 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100 - ●
−100 ≤ node.val ≤ 100; −1000 ≤ target ≤ 1000 - ●
The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child - ●
A route starts at the root and ends at a leaf (a node with no children). Return every route whose values add up to exactly target, each as the list of its node values from the root down. List the routes in left-to-right order of their leaves
root =
target =