124. Binary Tree Maximum Path Sum

Hard

Problem Description

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.
Jump to Solution: Python Java C++ JavaScript C#

Python Solution


# 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:
    max_sum = float('-inf')
    
    def max_gain(node):
        nonlocal max_sum
        if not node:
            return 0
        
        # Get max gain from left and right subtrees
        left_gain = max(max_gain(node.left), 0)
        right_gain = max(max_gain(node.right), 0)
        
        # Current path sum including node and both subtrees
        current_path_sum = node.val + left_gain + right_gain
        
        # Update max_sum if current path is larger
        max_sum = max(max_sum, current_path_sum)
        
        # Return maximum gain for parent node
        return node.val + max(left_gain, right_gain)
    
    max_gain(root)
    return max_sum

Java Solution


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int maxSum = Integer.MIN_VALUE;
    
    public int maxPathSum(TreeNode root) {
        maxGain(root);
        return maxSum;
    }
    
    private int maxGain(TreeNode node) {
        if (node == null) {
            return 0;
        }
        
        // Get max gain from left and right subtrees
        int leftGain = Math.max(maxGain(node.left), 0);
        int rightGain = Math.max(maxGain(node.right), 0);
        
        // Current path sum including node and both subtrees
        int currentPathSum = node.val + leftGain + rightGain;
        
        // Update maxSum if current path is larger
        maxSum = Math.max(maxSum, currentPathSum);
        
        // Return maximum gain for parent node
        return node.val + Math.max(leftGain, rightGain);
    }
}

C++ Solution


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int maxSum = INT_MIN;
    
    int maxGain(TreeNode* node) {
        if (!node) {
            return 0;
        }
        
        // Get max gain from left and right subtrees
        int leftGain = max(maxGain(node->left), 0);
        int rightGain = max(maxGain(node->right), 0);
        
        // Current path sum including node and both subtrees
        int currentPathSum = node->val + leftGain + rightGain;
        
        // Update maxSum if current path is larger
        maxSum = max(maxSum, currentPathSum);
        
        // Return maximum gain for parent node
        return node->val + max(leftGain, rightGain);
    }
    
public:
    int maxPathSum(TreeNode* root) {
        maxGain(root);
        return maxSum;
    }
};

JavaScript Solution


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxPathSum = function(root) {
    let maxSum = -Infinity;
    
    const maxGain = (node) => {
        if (!node) {
            return 0;
        }
        
        // Get max gain from left and right subtrees
        const leftGain = Math.max(maxGain(node.left), 0);
        const rightGain = Math.max(maxGain(node.right), 0);
        
        // Current path sum including node and both subtrees
        const currentPathSum = node.val + leftGain + rightGain;
        
        // Update maxSum if current path is larger
        maxSum = Math.max(maxSum, currentPathSum);
        
        // Return maximum gain for parent node
        return node.val + Math.max(leftGain, rightGain);
    };
    
    maxGain(root);
    return maxSum;
};

C# Solution


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    private int maxSum = int.MinValue;
    
    public int MaxPathSum(TreeNode root) {
        MaxGain(root);
        return maxSum;
    }
    
    private int MaxGain(TreeNode node) {
        if (node == null) {
            return 0;
        }
        
        // Get max gain from left and right subtrees
        int leftGain = Math.Max(MaxGain(node.left), 0);
        int rightGain = Math.Max(MaxGain(node.right), 0);
        
        // Current path sum including node and both subtrees
        int currentPathSum = node.val + leftGain + rightGain;
        
        // Update maxSum if current path is larger
        maxSum = Math.Max(maxSum, currentPathSum);
        
        // Return maximum gain for parent node
        return node.val + Math.Max(leftGain, rightGain);
    }
}

Complexity Analysis

Solution Explanation

This solution uses a recursive DFS approach:

Key points: