Skip to content
BytePatterns

Best Path Sum Between Any Nodes

HardTrees & BST#post-order#tree-dp#global-best~35m

Problem

An org chart is a binary tree where each node holds a profit or loss as an integer, possibly negative. A path is any sequence of nodes joined by parent-child edges that never visits a node twice; it does not have to pass through the root, and it has at least one node. Return the largest sum of node values along any path. The tree has up to 30,000 nodes with values between -1,000 and 1,000.

Examples

Input:  tree = -10, left 9, right 20 (children 15 and 7)
Output: 42
Why:    the path 15 -> 20 -> 7 skips the loss at the root
Input:  tree = 1, left 2, right 3
Output: 6
Input:  tree = -3
Output: -3
Why:    edge case, a path needs at least one node even when every value is negative

Hints

0 / 3

Stuck on the idea rather than the code? Diameter of a Tree covers it.