Algo-Sim › Binary Trees & BST

Binary Tree Maximum Path Sum

Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Each node returns its best downward gain (dropping negative sides) while the answer tries every node as the top of a path that bends there.

Problem

A path is a sequence of nodes where each pair of neighbours is joined by an edge, and no node appears twice; it does not need to pass through the root. Its sum is the sum of its values. Given the root of a binary tree with at least one node, return the largest sum of any non-empty path.

Constraints

Edge cases to test

Follow-up questions

Why drop a negative side?
A path can stop at the node instead, so a negative gain only lowers the sum: use max(0, gain).
Why does the function return one side only?
A path coming up through a parent can’t take both branches; only the bent path at a node uses both.

Solution

Java

private int best = Integer.MIN_VALUE;

public int maxPathSum(TreeNode root) {
    gain(root);
    return best;
}

private int gain(TreeNode node) {
    if (node == null) return 0;
    int left = Math.max(gain(node.left), 0);
    int right = Math.max(gain(node.right), 0);
    best = Math.max(best, node.val + left + right);
    return node.val + Math.max(left, right);
}

Python

def max_path_sum(root):
    best = float("-inf")

    def gain(node):
        nonlocal best
        if not node:
            return 0
        left = max(gain(node.left), 0)
        right = max(gain(node.right), 0)
        best = max(best, node.val + left + right)
        return node.val + max(left, right)

    gain(root)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int best = INT_MIN;

    int maxPathSum(TreeNode *root) {
        gain(root);
        return best;
    }

    int gain(TreeNode *node) {
        if (node == nullptr)
            return 0;
        int left = std::max(gain(node->left), 0);
        int right = std::max(gain(node->right), 0);
        best = std::max(best, node->val + left + right);
        return node->val + std::max(left, right);
    }
};

More Binary Trees & BST problems