Skip to content

Maximum Sum BST in Binary Tree

Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Example 1 tree; the subtree rooted at 3 is the best BST

Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.

Example 2:

Example 2 tree

Input: root = [4,3,null,1,2]
Output: 2
Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.

Example 3:

Input: root = [-4,-2,-5]
Output: 0
Explanation: All values are negatives. Return an empty BST.

Constraints:

  • The number of nodes in the tree is in the range [1,4×104][1, 4 \times 10^4].
  • −4×104≤-4 \times 10^4 \le Node.val ≤4×104\le 4 \times 10^4

A subtree rooted at node is a BST exactly when

  1. both child subtrees are BSTs, and
  2. node->val is greater than the largest key on the left and smaller than the smallest key on the right.

So whether a subtree is a BST — and its sum — can be decided from four facts about each child: is it a BST, its minimum, its maximum and its sum. A post-order traversal computes these bottom-up, visiting every node once instead of re-validating every subtree from scratch (O(n2)O(n^2)).

An empty child is a BST with min = +inf and max = -inf, so it never violates condition 2. Since the empty tree is allowed (Example 3), the answer starts at 0.

  1. dfs(node) returns an Info {isBST, mn, mx, sum} for the subtree.
  2. For nullptr, return {true, INT_MAX, INT_MIN, 0}.
  3. Compute L = dfs(node->left) and R = dfs(node->right).
  4. If L.isBST && R.isBST && L.mx < node->val && node->val < R.mn, the subtree is a BST: its sum is L.sum + R.sum + node->val; update best; return {true, min(L.mn, node->val), max(R.mx, node->val), sum}.
  5. Otherwise return {false, ...} — the other fields no longer matter, because no ancestor can be a BST either.
  6. maxSumBST calls dfs(root) and returns best.

Example 1, with the Info each call returns (sum only shown for BST subtrees). Green subtrees are BSTs; the subtree rooted at 3 has the largest sum, 20:

Example 1 tree with each subtree marked BST or not BST; the subtree rooted at 3 has the largest sum, 20

The node 4 fails because its right child has the same key (4 < R.mn is false). The root 1 then fails because its left subtree is not a BST, even though 1 < 2 holds on the right.

  • Time: O(n)O(n) — each node is visited once with O(1)O(1) work.
  • Space: O(h)O(h) — recursion stack, where h is the tree height (O(n)O(n) for a skewed tree).
  • All values negative (Example 3): every BST sum is negative, so best stays 0 (the empty BST).
  • Duplicate keys, e.g. 4 with a left child 4: the strict checks L.mx < node->val and node->val < R.mn reject them, as the definition requires.
  • Sentinels: keys lie in [−4×104,4×104][-4 \times 10^4, 4 \times 10^4], so INT_MAX/INT_MIN can never collide with a real key, and the largest sum 4×104⋅4×104=1.6×1094 \times 10^4 \cdot 4 \times 10^4 = 1.6 \times 10^9 fits in an int.

Think before you peek

Work out an approach on your own first — the explanation will still be here when you want it.

class Solution {
struct Info {
bool isBST;
int mn, mx, sum;
};
int best = 0;
Info dfs(TreeNode* node) {
if (!node) return {true, INT_MAX, INT_MIN, 0};
Info L = dfs(node->left), R = dfs(node->right);
if (L.isBST && R.isBST && L.mx < node->val && node->val < R.mn) {
int sum = L.sum + R.sum + node->val;
best = max(best, sum);
return {true, min(L.mn, node->val), max(R.mx, node->val), sum};
}
return {false, 0, 0, 0};
}
public:
int maxSumBST(TreeNode* root) {
dfs(root);
return best;
}
};
class Solution {
private record Info(boolean isBST, int mn, int mx, int sum) {}
private int best = 0;
private Info dfs(TreeNode node) {
if (node == null) return new Info(true, Integer.MAX_VALUE, Integer.MIN_VALUE, 0);
Info L = dfs(node.left), R = dfs(node.right);
if (L.isBST() && R.isBST() && L.mx() < node.val && node.val < R.mn()) {
int sum = L.sum() + R.sum() + node.val;
best = Math.max(best, sum);
return new Info(true, Math.min(L.mn(), node.val), Math.max(R.mx(), node.val), sum);
}
return new Info(false, 0, 0, 0);
}
public int maxSumBST(TreeNode root) {
dfs(root);
return best;
}
}
from math import inf
class Solution:
def maxSumBST(self, root: TreeNode | None) -> int:
# Post-order DFS with an explicit stack (a skewed tree is too deep for recursion).
# info[node] = (isBST, mn, mx, sum); an empty child is (True, inf, -inf, 0).
empty = (True, inf, -inf, 0)
info = {}
best = 0
stack = [(root, False)]
while stack:
node, children_done = stack.pop()
if node is None:
continue
if not children_done:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
continue
l_bst, l_mn, l_mx, l_sum = info.pop(node.left, empty)
r_bst, r_mn, r_mx, r_sum = info.pop(node.right, empty)
if l_bst and r_bst and l_mx < node.val < r_mn:
s = l_sum + r_sum + node.val
best = max(best, s)
info[node] = (True, min(l_mn, node.val), max(r_mx, node.val), s)
else:
info[node] = (False, 0, 0, 0)
return best

Give it a try first

Attempt the problem on LeetCode — the code will still be here.