Skip to content

Binary Tree Maximum Path Sum

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path. Return the maximum path sum of any non-empty path.

InputOutputPath
[1,2,3]62 → 1 → 3
[-10,9,20,null,null,15,7]4215 → 20 → 7
  • The number of nodes is in the range [1, 3000].
  • -1000 <= Node.val <= 1000
ApproachTimeSpaceBest When
Post-Order DFS + list trackingO(n)O(h)Explicit max_sum storage
DFS with reference parameterO(n)O(h)Cleaner max tracking
★ Recommended

Use post-order DFS. At each node, compute max path through it and update global max. Return max single-path gain.

⏱ Time O(n) Visit each node once 💾 Space O(h) Recursion depth
binary_tree_maximum_path_sum_postorder_dfs.py
from typing import Optional
# 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
def maxPathSum(root: Optional[TreeNode]) -> int:
"""
Find maximum path sum in binary tree using post-order DFS.
A path can pass through any node (not just root to leaf).
Time: O(n), Space: O(h) for recursion stack
"""
max_sum = [float('-inf')]
def dfs(node):
if not node:
return 0
# Max gain from left and right subtrees (at least 0 if negative)
left_gain = max(0, dfs(node.left))
right_gain = max(0, dfs(node.right))
# Max path through this node (may bend at this node)
max_path_through_node = node.val + left_gain + right_gain
max_sum[0] = max(max_sum[0], max_path_through_node)
# Return max path extending downward from this node
return node.val + max(left_gain, right_gain)
dfs(root)
return max_sum[0]
# Test cases
if __name__ == "__main__":
# Example 1: [1,2,3]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(maxPathSum(root)) # 6 (path: 2 -> 1 -> 3)
# Example 2: [-10,9,20,null,null,15,7]
root2 = TreeNode(-10)
root2.left = TreeNode(9)
root2.right = TreeNode(20)
root2.right.left = TreeNode(15)
root2.right.right = TreeNode(7)
print(maxPathSum(root2)) # 42 (path: 15 -> 20 -> 7)
# Example 3: Single negative node
single = TreeNode(-3)
print(maxPathSum(single)) # -3

Approach 2: DFS with Reference Max Tracking

Section titled “Approach 2: DFS with Reference Max Tracking”
alternative

Pass max_sum as mutable reference. Update during traversal. Same logic, different max tracking style.

⏱ Time O(n) Visit each node once 💾 Space O(h) Recursion depth
binary_tree_maximum_path_sum_dfs_max_tracking.py
from typing import Optional
# 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 __init__(self):
self.max_sum = float('-inf')
def maxPathSum(self, root: Optional[TreeNode]) -> int:
"""
Find maximum path sum using DFS with class-level max tracking.
Maintains max_sum as instance variable updated during traversal.
Time: O(n), Space: O(h) for recursion stack
"""
def dfs(node):
if not node:
return 0
# Max single-path sum extending from this node
left_sum = max(0, dfs(node.left))
right_sum = max(0, dfs(node.right))
# Path bending at this node
path_sum = node.val + left_sum + right_sum
self.max_sum = max(self.max_sum, path_sum)
# Return best single path extending downward
return node.val + max(left_sum, right_sum)
dfs(root)
return self.max_sum
# Test cases
if __name__ == "__main__":
# Example 1: [1,2,3]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
sol = Solution()
print(sol.maxPathSum(root)) # 6 (path: 2 -> 1 -> 3)
# Example 2: [-10,9,20,null,null,15,7]
root2 = TreeNode(-10)
root2.left = TreeNode(9)
root2.right = TreeNode(20)
root2.right.left = TreeNode(15)
root2.right.right = TreeNode(7)
sol2 = Solution()
print(sol2.maxPathSum(root2)) # 42 (path: 15 -> 20 -> 7)
# Example 3: Single negative node
single = TreeNode(-3)
sol3 = Solution()
print(sol3.maxPathSum(single)) # -3