Home
DSA Visualizer
Dynamic Programming
Max Path Sum
Max Path Sum
The binary tree maximum path sum problem asks for the largest sum of any path in a binary tree, where the path can start and end at any node.
DESCEND
Best path
—
Exploring node -10...
Next
Exploring node 9...
Intuition
We need to find a path that maximizes the sum of node values. A path can go up from a left child to the root and then down to the right child. For any node, the max path passing through it (as the highest point) is node.val + max_gain_from_left + max_gain_from_right.
Concept
Tree DP (Post-order Traversal):
We solve this using recursion. For each node, we want two things:
- To Parent: The max path sum starting at this node and going down (to be used by its parent). This is
node.val + max(left_gain, right_gain). - Global Max: The max path sum that pivots at this node. This is
node.val + left_gain + right_gain. We update a global variable with this value.
Note: If a gain is negative, we ignore it (take 0 instead).
How it Works
Algorithm:
- Initialize
globalMaxto negative infinity. - Perform a post-order traversal (Left, Right, Root).
- For
node: - Recursively get
leftGain = max(0, dfs(node.left)). - Recursively get
rightGain = max(0, dfs(node.right)). - Update
globalMax = max(globalMax, node.val + leftGain + rightGain). - Return
node.val + max(leftGain, rightGain)to the parent.
Step-by-Step Breakdown
Visualizing the Tree:
- Bottom-Up: Leaf nodes return their value (if positive).
- Combination: Internal nodes combine gains from children.
- Bridge: The "bridge" formed by
left -> root -> rightis potentially the max path.
When to Use
Applications:
- Network routing (most profitable path).
- Tree analysis (diameter, longest path).
When NOT to Use
- Graphs with Cycles: This algorithm assumes a tree structure (no cycles).
- Fixed Root/Leaf: If path must start at root or end at leaf, the logic simplifies.
How to Identify
"Binary tree", "Maximum path sum", "Any node to any node".
Applying for software engineering roles? Free, no sign-up:
