Maximum Sum BST in Binary Tree

Hard

Topics
TreeDFSBinary Search TreeDynamic Programming

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

244123456
best valid BST subtree
The shaded subtree is a valid BST and has the largest sum, 20.
Tree given in level-order (breadth-first); 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

1324
best valid BST subtree
Input:  root = [4,3,null,1,2]
Output: 2

Example 3

-2-4-5
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

  1. Recurse post-order, returning (isBST, min, max, sum).
  2. A null node returns (true, +inf, -inf, 0).
  3. A node is a BST when both children are and leftMax < node.val < rightMin.
  4. When valid, fold the sum into a running best and return the merged summary.
  5. 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 subtree

Complexity

  • 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.best
SensAI
Beta
Tap the mic to stop voice mode