AlgoInsight

DSA problem

Binary Tree Maximum Path Sum

HardTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop75AmazonMicrosoftGoogleMetaAppleBloomberg

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 appear in the sequence at most once. 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.

This is a quintessential post-order problem. The trick is to distinguish between two related but different quantities at every node:

  1. The path sum through the node — the best path that uses the node as its highest point. It looks like leftBestDown + node.val + rightBestDown, where leftBestDown and rightBestDown are the best downward paths from the node's children (each clamped to 0 because we are free to ignore a negative-sum branch).
  2. The best downward path from the node — what the node contributes to its parent. This is node.val + max(leftBestDown, rightBestDown), because a path that continues upward through the parent can only use one of the two children.

We do a single post-order DFS. At each node we compute both quantities; we use (1) to update a global best, and we return (2) upward. The base case is an empty subtree, which contributes 0 to whichever parent calls it (because that parent will clamp anything below 0 anyway).

The algorithm runs in O(n) time (each node visited once) and uses O(h) call-stack space.

Examples

Example 1
Input: root = [1,2,3]
Output: 6
Explanation: The best path is 2 → 1 → 3, summing to 6.
Example 2
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The best path is 15 → 20 → 7, summing to 42. The path does not need to pass through the root.
Example 3
Input: root = [-3]
Output: -3
Explanation: The path must be non-empty, so even a single negative node is a valid answer.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchdynamic-programming

Browse all DSA problems