Gamified challenge · Backtracking
The tunnels form a binary tree given as tree (a TreeNode root; examples are in level order with null for a missing chamber). Each chamber's number is its coins; cursed chambers have negative values. A treasure path starts at the root and ends at a leaf (a chamber with no tunnels below it), and its coins add up to exactly target.
Write paths(tree, target) that returns every treasure path as a list of coin values from root to leaf. The paths may be listed in any order, but each one must be listed once for every leaf it reaches. An empty tree has no paths.
For [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1] and target = 22 the answer is [[5, 4, 11, 2], [5, 8, 4, 5]].
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google