Adventure Book Gold

Easydepth-first searchAlso known as Path Sum

In a choose-your-own-adventure book, every page changes your purse: find 4 gold, pay a troll 2. Most pages let you choose between at most two next pages; a page with no choices is an ending. You start on the first page with 0 gold, and that page counts.

A puzzle at the back asks: can some ending be reached holding exactly a given amount?

Your task

Write exactGoldEnding(root, target). Each node's value is the gold change on that page. Return true if some path from the root down to a leaf (a node with no children) adds up to exactly target. Otherwise return false.

A path must end at a leaf; stopping on a page that still has a choice does not count. An empty book has no endings, so it returns false for every target. Trees are shown in level order, like [3, 4, -2, 6, 1, null, 5], with null marking a missing child. Your function receives real TreeNode objects with val, left and right.

exactGoldEnding(root: TreeNode, target: int) → bool

Examples

Example 1
Input
root = [3, 4, -2, 6, 1, null, 5]
target = 8
Output
true
Why

The three endings give 3 + 4 + 6 = 13, 3 + 4 + 1 = 8 and 3 + (-2) + 5 = 6. The path 3 → 4 → 1 ends with exactly 8 gold.

Example 2
Input
root = [3, 4, -2, 6, 1, null, 5]
target = 7
Output
false
Why

After pages 3 and 4 you hold 7 gold, but page 4 is not an ending, and both its choices change your purse. The endings give 13, 8 and 6, so none has exactly 7.

Constraints

  • 0 ≤ number of pages ≤ 1,000
  • -1,000 ≤ gold change on a page ≤ 1,000
  • -1,000,000 ≤ target ≤ 1,000,000
  • The tree is at most 500 levels deep.
Start with brute force

List every path from the first page to an ending, add up each, and check for the target.

Correct, but it stores whole paths and re-adds their shared beginnings, which in a long book can be hundreds of pages. Carrying one running number down the tree adds each page once.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code