Skip to the code
cf.
+50 XP

#350 Best Scoring Route Through a Widget Tree

hard

An onboarding tour moves through a tree of dashboard widgets along parent-child links. Each widget has a score, which can be negative when a widget is confusing. A route is any path of one or more widgets connected by edges, never visiting a widget twice. It may start and end anywhere and doesn't have to pass through the root.

Write bestRoute(root) that returns the largest possible sum of scores along a route. The tree has at least one node.

Example 1

Input: root = [2,4,5]
Output: 11

4 → 2 → 5 sums to 11.

Example 2

Input: root = [-30,9,20,null,null,15,-7]
Output: 35

15 → 20 sums to 35. Going on through the root costs -30 and only gains 9.

Constraints

  • 1 <= number of widgets <= 3 * 10^4
  • -1000 <= score <= 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).