๐ณ LeetCode 124: Binary Tree Maximum Path Sum โ A Complete Guide with Intuition and Java Solution
Difficulty: Hard
Topics: Binary Tree, Depth-First Search (DFS), Recursion, Dynamic Programming on Trees
๐ Introduction
Binary Trees are one of the most fascinating and frequently asked data structures in technical interviews. Among them, LeetCode Problem 124: Binary Tree Maximum Path Sum is a beautiful combination of recursion, tree traversal, and optimization.
In this post, weโll:
- Break down the problem statement
- Understand the intuitive approach
- Deep dive into the Java solution
- Walk through example cases step-by-step
- Discuss some practical insights and edge cases
๐ Problem Statement
You are given a binary tree, and you need to find the path with the maximum sum.
The Rules:
- A path is a sequence of nodes where each pair of adjacent nodes has a parent-child relationship.
- The path does not need to pass through the root.
- The path must contain at least one node.
- The path can start and end anywhere in the tree.
Your task:
Return the maximum sum obtainable from any such path.
๐งฎ Example 1:
1
/ \
2 3
Output: 6
๐ Explanation: The maximum path is 2 -> 1 -> 3
with a sum of 6
.
๐งฎ Example 2:
-10
/ \
9 20
/ \
15 7
Output: 42
๐ Explanation: The maximum path is 15 -> 20 -> 7
with a sum of 42
.
๐ Constraints
- The number of nodes: 1 to 30,000
- Node values: -1000 to 1000
๐งฉ Key Concepts to Understand
1. Path Sum Through a Node
For each node, there are two key things to consider:
Maximum sum that can be extended to the parent node
(This can only come from one side: either the left or the right subtree.)Maximum path sum passing through the current node
(This can include both left and right subtrees.)
2. Global Maximum vs. Local Path
- Each node contributes to a local path sum.
- The global maximum path sum should be updated if the local path at the current node exceeds the previously recorded maximum.
๐ง Intuition and Approach
We can use a post-order traversal (left โ right โ node) because:
- We need to compute the maximum path sum from the bottom up.
- Each nodeโs answer depends on its children.
Algorithm Steps:
- Traverse to the bottom of the tree using recursion.
- Calculate the maximum gain from the left and right subtrees.
- Ignore negative paths because they decrease the total sum. (
Math.max(leftGain, 0)
ensures this) - Calculate the maximum path sum passing through the current node.
- Update the global maximum sum if this local path is greater.
- Return the maximum gain to contribute to the parent.
๐ป Java Solution
class Solution {
private int maxSum = Integer.MIN_VALUE; // Global maximum path sum
public int maxPathSum(TreeNode root) {
maxGain(root);
return maxSum;
}
private int maxGain(TreeNode node) {
if (node == null) return 0;
// Calculate maximum gain from left and right children
int leftGain = Math.max(maxGain(node.left), 0); // Ignore negative paths
int rightGain = Math.max(maxGain(node.right), 0);
// Path sum including both left and right children
int currentMaxPath = node.val + leftGain + rightGain;
// Update global maximum if current path is better
maxSum = Math.max(maxSum, currentMaxPath);
// Return maximum gain to the parent
return node.val + Math.max(leftGain, rightGain);
}
}
๐ Step-by-Step Example
Letโs dry-run Example 2:
Input Tree:
-10
/ \
9 20
/ \
15 7
๐ ๏ธ Traversal and Computation:
Visit node 9 โ max gain: 9
Visit node 15 โ max gain: 15
Visit node 7 โ max gain: 7
Visit node 20 โ left gain: 15, right gain: 7 โ max path through 20: 15 + 20 + 7 = 42
Visit root -10 โ left gain: 9, right gain: 35 โ max path through root: 9 + (-10) + 35 = 34
โ Global max path sum: 42
โ Why Do We Ignore Negative Paths?
If the path sum of a subtree is negative, adding it to the parent will decrease the total sum.
Thatโs why we do:
int leftGain = Math.max(maxGain(node.left), 0);
๐ฑ Additional Tips
- Time Complexity: O(N), since we visit each node once.
- Space Complexity: O(H), where H is the height of the tree (due to the recursion stack).
๐ฉ Common Pitfalls:
- โ Forgetting to track the global maximum.
- โ Forgetting to return the correct gain to the parent (you canโt return both childrenโs gains because paths cannot split).
โจ Summary
This problem beautifully combines tree traversal with dynamic thinking.
Understanding when to split paths and when to choose one child is the core of solving it.
Hereโs what weโve learned:
- How to use post-order DFS to solve tree-based DP problems.
- How to correctly update global results from local computations.
- Why ignoring negative paths is essential.
โค๏ธ Connect & Share!
If you found this explanation helpful, consider sharing it with your fellow developers.
Letโs grow and learn together! ๐ฑ
You can also follow me for more posts on:
- Data Structures & Algorithms
- LeetCode Problem Guides
- Java and Backend Development
Top comments (0)