Binary Tree Maximum Path Sum - Problem
Binary Tree Maximum Path Sum - Find the path with the largest sum of node values in any binary tree.
A path in a binary tree is a sequence of connected nodes where you can move from parent to child or child to parent. The path doesn't need to start or end at the root - it can be any connected sequence of nodes. Each node can appear at most once in the path.
Your task is to find the path with the maximum sum of node values. The path must contain at least one node.
Examples:
• Tree:
• Tree:
Goal: Return the maximum sum of any valid path in the binary tree.
A path in a binary tree is a sequence of connected nodes where you can move from parent to child or child to parent. The path doesn't need to start or end at the root - it can be any connected sequence of nodes. Each node can appear at most once in the path.
Your task is to find the path with the maximum sum of node values. The path must contain at least one node.
Examples:
• Tree:
[1,2,3] → Maximum path sum: 6 (path: 2→1→3)• Tree:
[-10,9,20,null,null,15,7] → Maximum path sum: 42 (path: 15→20→7)Goal: Return the maximum sum of any valid path in the binary tree.
Input & Output
example_1.py — Basic Tree
$
Input:
root = [1,2,3]
›
Output:
6
💡 Note:
The optimal path is 2 → 1 → 3 with sum 2 + 1 + 3 = 6
example_2.py — Tree with Negative Values
$
Input:
root = [-10,9,20,null,null,15,7]
›
Output:
42
💡 Note:
The optimal path is 15 → 20 → 7 with sum 15 + 20 + 7 = 42. We skip the negative root -10.
example_3.py — Single Node
$
Input:
root = [-3]
›
Output:
-3
💡 Note:
The tree has only one node, so the maximum path sum is -3 (we must include at least one node).
Constraints
- The number of nodes in the tree is in the range [1, 3 × 104]
- -1000 ≤ Node.val ≤ 1000
- The tree is guaranteed to be non-empty
- Path must contain at least one node
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Problem
We need to find any path (not necessarily root to leaf) with maximum sum
2
Key Insight
At each node, track two things: max path through this node, and max path extending upward
3
Handle Negatives
Use max(0, childSum) to ignore paths that decrease our total
4
Global Maximum
Keep track of the best path found anywhere in the tree
Key Takeaway
🎯 Key Insight: The optimal solution elegantly handles the constraint that each node appears at most once by separating the calculation of paths passing through a node (for global maximum) versus paths extending upward to parent nodes (for recursive returns).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code