LeetCode 124. Binary Tree Maximum Path Sum
π§© Problem Description
Given the root
of a binary tree, return the maximum path sum of the tree.
A path is any sequence of nodes where each pair of adjacent nodes has an edge connecting them.
A path does not need to pass through the root and cannot revisit a node.
The path sum is the sum of node values along the path.
π¬ Examples
Example 1
1 | Input: root = [1,2,3] |
Example 2
1 | Input: root = [-10,9,20,null,null,15,7] |
π‘ Intuition
At each node, there are two different concepts:
Max Gain to Parent (what we can return upward):
max(node.val, node.val + leftGain, node.val + rightGain)
- This represents the best one-side path that can be extended by the parent.
Max Path Through Node (candidate for global answer):
node.val + max(0, leftGain) + max(0, rightGain)
- When a path goes through the current node and uses both sides (if beneficial).
- Negative gains should be treated as 0 (i.e., discard them).
We do a postorder DFS to compute gains bottom-up while maintaining a global maximum.
π’ Java Code (DFS + Global Tracking)
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n) β each node is visited once.
- Space Complexity: O(h) β recursion stack, where
h
is the height of the tree (O(n) worst case).
βοΈ Summary
- Use postorder DFS to compute the best upward gain and update a global maximum with the through-node path.
- Discard negative gains with
Math.max(0, ...)
so they donβt depress the total. - Classic pattern: **βreturn to parentβ vs update global answer.
Related problems
lc-543
β Diameter of Binary Tree (length vs sum idea)lc-687
β Longest Univalue Pathlc-437
β Path Sum III