Adventure Book Gold

Easydepth-first searchAlso known as Path Sum

In a choose-your-own-adventure book, every page changes your purse: you find 4 gold, or pay a troll 2. At the bottom of most pages you choose between at most two pages to read next. A page with no choices is an ending. You start with 0 gold on the first page, and that page counts too.

A reader wants to know if some ending can be reached holding exactly the number of gold coins a puzzle at the back of the book asks for.

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) has values adding 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], where null marks 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: you must keep reading, and both of its choices change your purse. The three endings give 13, 8 and 6, so no ending 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

Write out every path from the first page to an ending as a list of pages, add up each list, and check if any total equals the target.

It is correct, but it stores whole paths and re-adds the shared beginning of every path. In a long book where most paths share their first few hundred pages, that is a lot of repeated adding. Carrying one running number down the tree means each page is added exactly 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