Introduction
Maximum Path Sum means:
- finding path
with maximum total value
inside binary tree
The path:
- can start anywhere
- can end anywhere
- must remain connected
Goal:
- maximize total path sum
Example:
-10
/ \
9 20
/ \
15 7
Maximum Path:
15 → 20 → 7
Maximum Sum:42
Explanation:
The best path does not always pass through root node. This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5Approach : Recursive DFS Solution
Explanations:
Explanation:
The idea is:
- recursively calculate
maximum contribution
from every subtree - update global maximum sum
Steps:
- Visit current node.
- Calculate left contribution.
- Calculate right contribution.
- Ignore negative paths.
- Update maximum sum.
- Return best subtree path.
Formula:
node.value + leftContribution + rightContribution Return Formula:
node.value + max(leftContribution, rightContribution)This approach:
- uses DFS recursion
- combines subtree optimization
and path calculation
Dry Run
Visit:20
Left contribution:
15
Right contribution:
7
Current path sum:
42
Update maximum sum:
42
Return:
35
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation : Every tree node is visited once.
Space Complexity:- O(h) Explanation : Recursion stack depends on tree height.
Why This Problem is Important