Vineyard Tasting Route

Harddepth-first searchAlso known as Binary Tree Maximum Path Sum

A hillside vineyard is a network of plots joined by footpaths. From the visitor centre plot, at most two paths lead further up the hill, and so on from every plot, with no loops: a binary tree. Each plot has a score from last year's visitors. A great tasting scores high; a muddy, steep plot with a sour wine scores below zero.

The vineyard wants to print its best tasting route: a walk through connected plots that never visits a plot twice, starting and ending anywhere. The route's score is the sum of the plots on it. A route can be a single plot, and it does not have to include the visitor centre.

Your task

Write bestTastingRoute(root). A path is a sequence of nodes where each pair of neighbours is joined by an edge, and no node appears twice. Return the largest possible sum of node values over all non-empty paths in the tree.

The tree always has at least one node. Values can be negative, and so can the answer. Trees are shown in level order, like [-3, 9, 6, null, null, -2, 8], where null marks a missing child. Your function receives real TreeNode objects with val, left and right.

bestTastingRoute(root: TreeNode) → int

Examples

Example 1
Input
root = [-3, 9, 6, null, null, -2, 8]
Output
20
Why

The best route is 9 → -3 → 6 → 8, scoring 20. It passes through the visitor centre (-3) even though that plot loses points, because it connects 9 with 6 + 8 = 14. Avoiding it, the best is 6 → 8 = 14.

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

Plot 5 alone scores 5. Every longer route that includes it must pass through -6: 4 → -6 → 5 scores 3, and 5 → -6 → 2 scores 1. Here the best route is a single plot, far from the visitor centre.

Constraints

  • 1 ≤ number of plots ≤ 1,000
  • -1,000 ≤ score ≤ 1,000
  • The tree is at most 500 levels deep.
Start with brute force

Try every pair of plots as the two ends of the route, walk the unique path between them, and add up its scores. Keep the best.

With 1,000 plots there are about 500,000 pairs, and each path can be hundreds of plots long, so this runs into the hundreds of millions of steps: O(n²) pairs times O(h) per path. The waste is that neighbouring routes share most of their plots. Computing, for every plot, its best downward walk once, bottom-up, lets every turning point be checked in O(1).

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