A trip planner shows a decision tree of itinerary steps, each with a cost. The user wants every complete itinerary, from the top step down to a final step (a leaf), whose costs add up to exactly budget.
Write routesWithin(root, budget) that returns every such root-to-leaf path as an array of values, in left-to-right order of their leaves (the order a depth-first walk that tries left before right finds them). If there are none, return [].
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], budget = 22 Output: [[5,4,11,2],[5,8,4,5]]
Both paths add up to 22; the left one is found first.
Input: root = [1,2,3], budget = 5 Output: []
The two paths add up to 3 and 4.
0 <= number of steps <= 5000-1000 <= cost <= 1000Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.
Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #355 All Routes Hitting a Budget. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.