#124

Binary Tree Maximum Path Sum

Hard
Dynamic ProgrammingTreeDepth-First SearchBinary TreeDepth-First SearchDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution uses depth-first search (DFS) to calculate the maximum path sum efficiently. It keeps track of the maximum path sum at each node while ensuring that we only consider paths that contribute positively to the sum.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum path sum found.
  2. 2Step 2: Use DFS to traverse the tree, calculating the maximum contribution of each node to the path sum.
  3. 3Step 3: For each node, calculate the maximum path sum that can be formed by including its left and right children.
  4. 4Step 4: Update the global maximum path sum if the current node's path sum exceeds it.
solution.py22 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def maxPathSum(self, root: TreeNode) -> int:
10        max_sum = float('-inf')
11
12        def dfs(node):
13            nonlocal max_sum
14            if not node:
15                return 0
16            left = max(dfs(node.left), 0)
17            right = max(dfs(node.right), 0)
18            max_sum = max(max_sum, left + right + node.val)
19            return node.val + max(left, right)
20
21        dfs(root)
22        return max_sum

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursive call stack, where h is the height of the tree.

  • 1The maximum path sum can be found by considering paths that may not pass through the root.
  • 2Using DFS allows us to explore all potential paths efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.