Binary Tree Post-Order DFS: Return vs. Global Split
Compute tree-wide optima (max path sum, diameter, LCA) by returning a single extendable branch while updating a two-branch split answer.
The core idea
In bottom-up tree problems, what you return to your parent is often stricter than the global answer you update at the current node. A path peaking at node can combine both left and right subtrees (node.val + L + R), but any path continuing above node can only extend through one branch (node.val + max(L, R)).
Watch it run
Step through the trace below (or turn on Predict Mode) to watch how node 20 updates best = 42 while returning 35 to -10.
Key Takeaway
Canonical Python template
def max_path_sum(root) -> int:
best = float("-inf")
def dfs(node) -> int:
nonlocal best
if not node:
return 0
left = max(0, dfs(node.left))
right = max(0, dfs(node.right))
best = max(best, node.val + left + right)
return node.val + max(left, right)
dfs(root)
return int(best)