Skip to main content

🟥 Binary Tree Maximum Path Sum (#124)

📋 Problem Statement

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.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

💡 Examples

Example 1

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

🔑 Key Insights & Approach

Core Observation: At each node, max path can:

  1. Go through node as split point (left + node + right)
  2. Continue from node to parent (node + max(left, right))

Track global max for case 1, return case 2 to parent.

Why Post-order DFS?

  • O(n) time, O(h) space
  • Need child results before processing node
  • Handle negative paths by using max(0, child)

Approaches:

  1. Post-order DFS with global max: O(n) time, O(h) space - optimal

Pattern: "Tree Path Sum" with split point consideration.

🐍 Solution: Python

Approach: Post-order DFS with Global Max

Time Complexity: O(n) | Space Complexity: O(h)

from typing import Optional

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:
self.max_sum = float('-inf')

def dfs(node):
if not node:
return 0

# Get max path sum from left and right (ignore negative)
left_max = max(dfs(node.left), 0)
right_max = max(dfs(node.right), 0)

# Update global max (path through current node)
current_max = node.val + left_max + right_max
self.max_sum = max(self.max_sum, current_max)

# Return max path sum continuing to parent
return node.val + max(left_max, right_max)

dfs(root)
return self.max_sum

🔵 Solution: Golang

Approach: Post-order DFS

Time Complexity: O(n) | Space Complexity: O(h)

import "math"

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func maxPathSum(root *TreeNode) int {
maxSum := math.MinInt32

var dfs func(node *TreeNode) int
dfs = func(node *TreeNode) int {
if node == nil {
return 0
}

// Get max from left and right (ignore negative)
leftMax := max(dfs(node.Left), 0)
rightMax := max(dfs(node.Right), 0)

// Update global max
currentMax := node.Val + leftMax + rightMax
if currentMax > maxSum {
maxSum = currentMax
}

// Return max path continuing to parent
return node.Val + max(leftMax, rightMax)
}

dfs(root)
return maxSum
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

📚 References