Vineyard Tasting Route

Harddepth-first searchAlso known as Binary Tree Maximum Path Sum

A hillside vineyard's plots are joined by footpaths. From the visitor centre, and from every plot after it, at most two paths lead further up, and there are no loops, so the plots form a binary tree. Each plot has a visitor score, and a muddy plot with sour wine scores below zero.

The vineyard wants its best tasting route: a walk through connected plots, never visiting one twice, starting and ending anywhere. Its score is the sum of its plots. A route can be a single plot and need not 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 route ends, walk the unique path between them, and keep the best sum.

With 1,000 plots that is about 500,000 pairs, each path up to hundreds of plots long: O(n²) pairs times O(h) per path, hundreds of millions of steps. Neighbouring routes share most of their plots. Computing each plot's 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