DEV Community

Cover image for LeetCode 124: Binary Tree Maximum Path Sum โ€“ Full Explanation & Java Solution

๐ŸŒณ 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

Enter fullscreen mode Exit fullscreen mode

Output: 6

๐Ÿ‘‰ Explanation: The maximum path is 2 -> 1 -> 3 with a sum of 6.


๐Ÿงฎ Example 2:

  -10
  /  \
 9   20
     / \
    15  7

Enter fullscreen mode Exit fullscreen mode

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:

  1. Traverse to the bottom of the tree using recursion.
  2. Calculate the maximum gain from the left and right subtrees.
  3. Ignore negative paths because they decrease the total sum. (Math.max(leftGain, 0) ensures this)
  4. Calculate the maximum path sum passing through the current node.
  5. Update the global maximum sum if this local path is greater.
  6. 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŒŸ Step-by-Step Example
Letโ€™s dry-run Example 2:

Input Tree:
      -10
      /  \
     9   20
         / \
        15  7

Enter fullscreen mode Exit fullscreen mode

๐Ÿ› ๏ธ 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
Enter fullscreen mode Exit fullscreen mode

โœ… 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);
Enter fullscreen mode Exit fullscreen mode

๐ŸŒฑ 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)