Exact Budget Trail
Easy · Trees & BSTs · about 15 min
A choose-your-own-adventure trip planner is a binary tree. Each stop has a cost (it can be negative: some stops pay you back). A trip starts at the root and keeps choosing a child until it reaches an end stop: a stop with no children at all. The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.
Return True / true if some trip from the root to an end stop costs exactly target in total, otherwise False / false. An empty planner has no trips, so the answer is False / false for any target.
- Up to 5,000 stops, costs between -1000 and 1000.
Examples:
has_exact_trail([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1], 22) → True (5 + 4 + 11 + 2)
has_exact_trail([1, 2], 1) → False (the root has a child, so it is not an end stop)
Hints
- Carry the amount still left to spend as you go down.
- Only check the amount at a stop with no left child AND no right child.
- Costs can be negative, so going over the target part way is not a reason to stop.
Learn the pattern first: the Trees & BSTs lesson.
More Trees & BSTs problems
- Levels in the Org Chart (Easy)
- Mirror the Folder Tree (Easy)
- Twin Backup Check (Easy)
- Shared Boss in the ID Tree (Easy)
- Floor-by-Floor Roster (Medium)
- Unbeaten on the Way Down (Medium)
- Longest Handoff Chain (Medium)
- Shelf Index Check (Medium)
- K-th Cheapest Price (Medium)
- Closest Shared Folder (Medium)
- Rebuild the Bracket (Medium)
- Best Relay Route (Hard)
- Downhill Trails With a Target Sum (Hard)
- Office Wi-Fi Repeaters (Hard)