Binary Tree Maximum Path Sum
hard
binary-tree
depth-first-search
dynamic-programming
Given a non-empty binary tree, return the maximum path sum. A path may start and end at any two nodes, but it must move only along parent-child connections, and it cannot reuse a node. The path does not need to pass through the root.
Input / output
- Input:
root: TreeNoderepresented by a level-order array withnullplaceholders - Output: integer maximum path sum
Examples
root = [1,2,3]returns6for the path2 -> 1 -> 3.root = [-10,9,20,null,null,15,7]returns42for the path15 -> 20 -> 7.root = [2,-1]returns2because taking the root alone is best.
Constraints
- The number of nodes is in the range
[1, 3 * 10^4] -1000 <= node.val <= 1000
Target complexity
- Aim for
O(n)time with one depth-first traversal andO(h)call-stack space.
Hints
- For each node, distinguish between the best path you can extend upward to its parent and the best complete path that bends through this node.
- Negative child contributions should usually be dropped instead of extended.
Follow-up How would you modify the DFS if the interviewer asked for the actual node values on one maximum-sum path, not just the sum?
Examples
Example 1
Input: root = [1,2,3]
Output: 6
Example 2
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Example 3
Input: root = [2,-1]
Output: 2
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.