Binary Tree Maximum Path Sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes has an edge. Return the maximum path sum of any non-empty path.
Examples
root = [1,2,3]
6
The maximum path sum is 2 -> 1 -> 3 with sum 6.
root = [-10,9,20,null,null,15,7]
42
The maximum path sum is 15 -> 20 -> 7 with sum 42.
Constraints
- •
The number of nodes in the tree is in the range [1, 3 * 10^4] - •
-1000 <= Node.val <= 1000
Approaches
Compute all possible paths and find the maximum sum.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_path_sum(root):
max_sum = float('-inf')
def dfs(node):
nonlocal max_sum
if not node:
return 0
left = max(dfs(node.left), 0)
right = max(dfs(node.right), 0)
max_sum = max(max_sum, node.val + left + right)
return node.val + max(left, right)
dfs(root)
return max_sumUse DFS to compute max gain from each node while tracking global max.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_path_sum(root):
max_sum = float('-inf')
def dfs(node):
nonlocal max_sum
if not node:
return 0
left = max(dfs(node.left), 0)
right = max(dfs(node.right), 0)
max_sum = max(max_sum, node.val + left + right)
return node.val + max(left, right)
dfs(root)
return max_sumSame approach with cleaner implementation.
Diagram
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_path_sum(root):
self.max_sum = float('-inf')
def dfs(node):
if not node:
return 0
left = max(dfs(node.left), 0)
right = max(dfs(node.right), 0)
self.max_sum = max(self.max_sum, node.val + left + right)
return node.val + max(left, right)
dfs(root)
return self.max_sumComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Brute Force - All Paths | O(n^2) | O(h) | Compute all possible paths and find the maximum sum. |
| DFS with Global Max | O(n) | O(h) | Use DFS to compute max gain from each node while tracking global max. |
| Optimized DFS | O(n) | O(h) | Same approach with cleaner implementation. |
Compute all possible paths and find the maximum sum.
Use DFS to compute max gain from each node while tracking global max.
Same approach with cleaner implementation.
Common Mistakes
Not ignoring negative contributions from children (max with 0)
Forgetting that the path can start and end at any node
Trying to return the path sum instead of the max gain from a subtree