Solve LeetCode 124: Binary Tree Maximum Path Sum in Python with a postorder gain DP approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete 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 |
What the problem is testing
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.
Algorithm
- 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.
- Maintain this invariant: The returned gain is the best path starting at the node and extending through at most one child.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
LeetCode provides the list, tree, or graph node definition used by the method.
from collections import Counter, defaultdict, deque, OrderedDict
import random
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 bestWhy this is correct
The proof follows the maintained state: The returned gain is the best path starting at the node and extending through at most one child. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(n) time and O(h) recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Negative child gains are discarded; an all-negative tree returns its largest node.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 129. Sum Root to Leaf Numbers · Next: 173. Binary Search Tree Iterator