Skip to the code
cf.
+25 XP

#355 All Routes Hitting a Budget

medium

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

Example 1

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.

Example 2

Input: root = [1,2,3], budget = 5
Output: []

The two paths add up to 3 and 4.

Constraints

  • 0 <= number of steps <= 5000
  • -1000 <= cost <= 1000

Trees 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.

Saved in this browser

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).