Binary Tree Maximum Path Sum
HardNeetCode 150Top Interview 150 TreesBaiduDoorDashWixProblem
A path in a binary tree is a chain of nodes where each neighbouring pair is joined by an edge and no node appears twice. The path does not have to pass through the root, and it must contain at least one node.
Given the root of a binary tree, return the largest possible sum of the values on any path.
The tree is given in level order, with null for a missing child.
Constraints
- 1 ≤ number of nodes ≤ 30000
- -1000 ≤ Node.val ≤ 1000
Examples: pick one to animate
Solutions
Time: Every node is visited once, and each visit does constant work.
Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.
The best path has a highest node, where it bends. Through that node the sum is its value plus the best downward gain on each side. A side with a negative gain is dropped (use 0 instead). So compute gains bottom-up: at each node try value + left + right as a candidate for the answer, then report value plus the larger side upward, because a parent can extend only one branch. Keep the largest candidate seen.