Binary Tree Maximum Path Sum
LeetCode 124 · Hard · solution, intuition & step-by-step walkthrough
Update the answer with both sides; return only one side to the parent.
This is how I solved Binary Tree Maximum Path Sum (LeetCode 124), a hard problem from the Tree DP pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every path has a highest node where it bends. At each node, the best path bending there is node + best downward gain from the left + best downward gain from the right. But a path passed up to the parent can only continue down one side, so return node + the better single side. Negative gains are dropped as 0.
Approach
- 1
dfs(node) returns the best downward path sum starting at node.
- 2
Left and right gains are clipped at 0 — a negative branch is better left out.
- 3
Update the global best with node.val + left + right (the bend at this node).
- 4
Return node.val + max(left, right) to the parent.
How I solved it
Post-order DFS (tree DP)PythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
max_sum = float("-inf")
def dfs(node):
nonlocal max_sum
if node==None:
return 0
left = max(0,dfs(node.left))
right = max(0,dfs(node.right))
max_sum=max(max_sum,node.val+left+right)
return node.val+max(left,right)
dfs(root)
return max_sumBinary Tree Maximum Path Sum — FAQ
What is the intuition behind Binary Tree Maximum Path Sum?
Every path has a highest node where it bends. At each node, the best path bending there is node + best downward gain from the left + best downward gain from the right. But a path passed up to the parent can only continue down one side, so return node + the better single side. Negative gains are dropped as 0.
How do you solve Binary Tree Maximum Path Sum (LeetCode 124)?
1. dfs(node) returns the best downward path sum starting at node. 2. Left and right gains are clipped at 0 — a negative branch is better left out. 3. Update the global best with node.val + left + right (the bend at this node). 4. Return node.val + max(left, right) to the parent.
What is the time and space complexity of Binary Tree Maximum Path Sum?
Time: O(n). Space: O(h) recursion. (Accepted approach: Post-order DFS (tree DP).)
What are common mistakes in Binary Tree Maximum Path Sum?
Start the global best at −∞ — an all-negative tree must return its largest value. Returning both sides to the parent would create a forked, invalid path.