KatInterview

124. Binary Tree Maximum Path Sum

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum path sum in a binary tree. A path is a sequence of connected nodes, and each node can appear at most once. The path does not have to include the root. This implies the path can start and end at any two nodes in the tree.

Solution

Binary Tree Maximum Path Sum in Python

# 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 maxPathSum(self, root: Optional[TreeNode]) -> int:
        self.max_sum = float('-inf')

        def gain_from_subtree(node: Optional[TreeNode]) -> int:
            if not node:
                return 0

            # Recursively get the maximum gain from left and right subtrees.
            # A path gain can be negative, so we use max(0, ...) to discard negative gains.
            gain_from_left = max(0, gain_from_subtree(node.left))
            gain_from_right = max(0, gain_from_subtree(node.right))

            # The sum of a new path which includes the current node as the "highest" node.
            # This path cannot be extended to the parent of the current node.
            current_path_sum = node.val + gain_from_left + gain_from_right
            
            # Update the global maximum path sum.
            self.max_sum = max(self.max_sum, current_path_sum)
            
            # For the recursion up, return the maximum gain a path starting from the
            # current node can provide. It can only go one way (left or right).
            return node.val + max(gain_from_left, gain_from_right)

        gain_from_subtree(root)
        return int(self.max_sum)

Binary Tree Maximum Path Sum in Java

/**
 * 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;

    public int maxPathSum(TreeNode root) {
        maxSum = Integer.MIN_VALUE;
        gainFromSubtree(root);
        return maxSum;
    }

    private int gainFromSubtree(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // Recursively get the maximum gain from left and right subtrees.
        // A path gain can be negative, so we use Math.max(0, ...) to discard negative gains.
        int gainFromLeft = Math.max(0, gainFromSubtree(node.left));
        int gainFromRight = Math.max(0, gainFromSubtree(node.right));

        // The sum of a new path which includes the current node as the "highest" node.
        // This path cannot be extended to the parent of the current node.
        int currentPathSum = node.val + gainFromLeft + gainFromRight;

        // Update the global maximum path sum.
        maxSum = Math.max(maxSum, currentPathSum);

        // For the recursion up, return the maximum gain a path starting from the
        // current node can provide. It can only go one way (left or right).
        return node.val + Math.max(gainFromLeft, gainFromRight);
    }
}

Binary Tree Maximum Path Sum in C++

/**
 * 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;

public:
    int maxPathSum(TreeNode* root) {
        maxSum = INT_MIN;
        gainFromSubtree(root);
        return maxSum;
    }

private:
    int gainFromSubtree(TreeNode* node) {
        if (node == nullptr) {
            return 0;
        }

        // Recursively get the maximum gain from left and right subtrees.
        // A path gain can be negative, so we use std::max(0, ...) to discard negative gains.
        int gainFromLeft = std::max(0, gainFromSubtree(node->left));
        int gainFromRight = std::max(0, gainFromSubtree(node->right));

        // The sum of a new path which includes the current node as the "highest" node.
        // This path cannot be extended to the parent of the current node.
        int currentPathSum = node->val + gainFromLeft + gainFromRight;

        // Update the global maximum path sum.
        maxSum = std::max(maxSum, currentPathSum);

        // For the recursion up, return the maximum gain a path starting from the
        // current node can provide. It can only go one way (left or right).
        return node->val + std::max(gainFromLeft, gainFromRight);
    }
};

Binary Tree Maximum Path Sum in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxPathSum(root: TreeNode | null): number {
    let maxSum = -Infinity;

    function gainFromSubtree(node: TreeNode | null): number {
        if (node === null) {
            return 0;
        }

        // Recursively get the maximum gain from left and right subtrees.
        // A path gain can be negative, so we use Math.max(0, ...) to discard negative gains.
        const gainFromLeft = Math.max(0, gainFromSubtree(node.left));
        const gainFromRight = Math.max(0, gainFromSubtree(node.right));

        // The sum of a new path which includes the current node as the "highest" node.
        // This path cannot be extended to the parent of the current node.
        const currentPathSum = node.val + gainFromLeft + gainFromRight;

        // Update the global maximum path sum.
        maxSum = Math.max(maxSum, currentPathSum);

        // For the recursion up, return the maximum gain a path starting from the
        // current node can provide. It can only go one way (left or right).
        return node.val + Math.max(gainFromLeft, gainFromRight);
    }

    gainFromSubtree(root);
    return maxSum;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.