LeetCode 124: Binary Tree Maximum Path Sum is a Hard binary tree general problem. This Python walkthrough develops a postorder gain DP solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Binary Tree General |
| Reusable pattern | postorder gain DP |
| Complexity | O(n) time and O(h) recursion space |
Recognizing the pattern
Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.
For this problem specifically, return the best downward gain from each node while updating a global answer with the path that uses both positive child gains through that node. The invariant worth writing beside the code is: The returned gain is the best path starting at the node and extending through at most one child.
Step-by-step algorithm
- Identify the input state consumed by
maxPathSum(root)and initialize the data required by the postorder gain DP pattern. - Return the best downward gain from each node while updating a global answer with the path that uses both positive child gains through that node.
- After each update, verify the page’s central invariant: The returned gain is the best path starting at the node and extending through at most one child.
- Finish only after the boundary behavior is covered: Negative child gains are discarded; an all-negative tree returns its largest node.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def maxPathSum(self, root):
best = float("-inf")
def gain(node):
nonlocal best
if not node:
return 0
left = max(0, gain(node.left))
right = max(0, gain(node.right))
best = max(best, node.val + left + right)
return node.val + max(left, right)
gain(root)
return bestReading the implementation
The main entry point is maxPathSum(root). The named working state includes best, left, right; those variables make the postorder gain DP state visible instead of hiding it in incidental control flow.
The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, return the best downward gain from each node while updating a global answer with the path that uses both positive child gains through that node.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Return the best downward gain from each node while updating a global answer with the path that uses both positive child gains through that node. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the returned gain is the best path starting at the node and extending through at most one child.
Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.
Complexity and trade-offs
O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().maxPathSum(tree([-10,9,20,None,None,15,7]))==42Common mistakes and edge cases
- Problem-specific boundary: Negative child gains are discarded; an all-negative tree returns its largest node.
- Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
- Invariant check: after every update, confirm that the returned gain is the best path starting at the node and extending through at most one child.
Interview review checklist
- Explain why postorder gain DP matches the structure of this input.
- State the invariant in one sentence before tracing code: The returned gain is the best path starting at the node and extending through at most one child.
- Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
- Test the boundary explicitly: Negative child gains are discarded; an all-negative tree returns its largest node.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 129. Sum Root to Leaf Numbers · Next: 173. Binary Search Tree Iterator