Maximum Sum BST in Binary Tree
Hard
Topics
Given the root of a binary tree, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). A valid BST requires every node in the left subtree to be strictly less than the node, and every node in the right subtree to be strictly greater. If no sub-tree is a BST with positive sum, return 0.
Example 1
null marks a missing child.Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20
Example 2
Input: root = [4,3,null,1,2] Output: 2
Example 3
Input: root = [-4,-2,-5] Output: 0
Constraints
- 1 <= number of nodes <= 4*10^4
- -4*10^4 <= Node.val <= 4*10^4.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A subtree is a BST only if both of its subtrees are, and the node's value fits strictly between the largest value on its left and the smallest on its right. That is information flowing upward, so a post-order traversal that returns a summary per node answers it in one pass.
The summary is four values: is this subtree a BST, its minimum, its maximum, and its sum. A missing child returns (true, +infinity, -infinity, 0), which is the identity for these comparisons — it makes a leaf automatically valid, since any value is below +infinity and above -infinity, and it makes the min and max collapse to the leaf's own value.
Choosing those sentinels is the whole craft here. With 0 or the node's value instead, leaves and single-child nodes need special cases.
Approach
- Recurse post-order, returning
(isBST, min, max, sum). - A null node returns
(true, +inf, -inf, 0). - A node is a BST when both children are and
leftMax < node.val < rightMin. - When valid, fold the sum into a running best and return the merged summary.
- When invalid, return a failed summary; the running best already holds anything worth keeping.
Dry Run
1
/ \
4 3
/ \ / \
2 4 2 5
/ \
4 6
node 2 (leaf, left of 4) (true, 2, 2, 2)
node 4 (leaf, right of 4) (true, 4, 4, 4)
node 4 left max 2 < 4 < right min 4? NO, 4 is not < 4
-> not a BST
node 2 (leaf) (true, 2, 2, 2)
node 4 (leaf) (true, 4, 4, 4)
node 6 (leaf) (true, 6, 6, 6)
node 5 4 < 5 < 6 -> BST, sum 15 <- best so far
node 3 left max 2 < 3 but right min 4, and 3 < 4 -> BST,
sum 2 + 3 + 15 = 20 <- new best
node 1 left child is not a BST -> not a BST
answer 20
the running best is kept at every valid node, not just at the root, because the
best BST is usually a proper subtreeComplexity
- Time — O(n): one visit per node, constant work each.
- Space — O(h) for the call stack. At the stated bound of 4×10⁴ nodes a degenerate path needs 40,000 frames, which exceeds Python's default limit of 1,000 and Java's default thread stack of roughly 20,000. The Python harness on this page raises the limit; an explicit stack is the portable fix.
Common Pitfalls
- Validating each subtree independently by an in-order walk. That is O(n²) and is the version the single-pass summary replaces.
- Using non-strict comparisons. The definition here demands strictly less and strictly greater, so a duplicate value breaks the BST property — the
4 / (2, 4)node above is exactly that case. - Choosing 0 as the sentinel min and max. With negative values allowed down to −4×10⁴, a 0 sentinel silently rejects valid subtrees.
- Only considering the root, or only maximal subtrees. The best BST is usually strictly inside a non-BST, which is why the answer is tracked at every valid node.
- Initialising the best at negative infinity. The problem says to return 0 when no BST has a positive sum, so 0 is the correct starting value.
- Returning the merged min and max from an invalid subtree and letting the parent use them. Once a subtree fails, its bounds are meaningless and must not propagate.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxSumBST(self, root):
self.best = 0
def dfs(node):
if not node: return (True, float('inf'), float('-inf'), 0)
lb, lmin, lmax, ls = dfs(node.left)
rb, rmin, rmax, rs = dfs(node.right)
if lb and rb and node.val > lmax and node.val < rmin:
s = ls + rs + node.val
if s > self.best: self.best = s
return (True, min(lmin, node.val), max(rmax, node.val), s)
return (False, 0, 0, 0)
dfs(root)
return self.bestimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int maxSumBST(TreeNode root) {
best = 0;
dfs(root);
return best;
}
int best;
private long[] dfs(TreeNode node) {
if (node == null) return new long[]{1, Long.MAX_VALUE, Long.MIN_VALUE, 0};
long[] l = dfs(node.left), r = dfs(node.right);
if (l[0] == 1 && r[0] == 1 && node.val > l[2] && node.val < r[1]) {
long s = l[3] + r[3] + node.val;
if (s > best) best = (int) s;
return new long[]{1, Math.min(l[1], node.val), Math.max(r[2], node.val), s};
}
return new long[]{0, 0, 0, 0};
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int maxSumBST(TreeNode* root) {
long long best = 0;
function<array<long long,4>(TreeNode*)> dfs = [&](TreeNode* node) -> array<long long,4> {
if (!node) return {
1, LLONG_MAX, LLONG_MIN, 0
};
array<long long,4> l = dfs(node->left), r = dfs(node->right);
if (l[0] == 1 && r[0] == 1 && node->val > l[2] && node->val < r[1]) {
long long s = l[3] + r[3] + node->val;
if (s > best) best = s;
return {
1, min(l[1], (long long)node->val), max(r[2], (long long)node->val), s
};
}
return {
0, 0, 0, 0
};
};
dfs(root);
return (int)best;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var maxSumBST = function(root) {
let best = 0;
const dfs = (node) => {
if (!node) return [true, Infinity, -Infinity, 0];
const l = dfs(node.left), r = dfs(node.right);
if (l[0] && r[0] && node.val > l[2] && node.val < r[1]) {
const s = l[3] + r[3] + node.val;
if (s > best) best = s;
return [true, Math.min(l[1], node.val), Math.max(r[2], node.val), s];
}
return [false, 0, 0, 0];
};
dfs(root);
return best;
};