Maximum Sum BST in Binary Tree Problem
Description
LeetCode Problem 1373.
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:

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:

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 * 10^4]. -4 * 10^4 <= Node.val <= 4 * 10^4
Solution
Approach: Post-Order DFS Returning Subtree Facts
Checking every subtree for the BST property from the top down repeats the same work many times. Instead, let each subtree report to its parent everything the parent needs, in a single post-order DFS. For a subtree we return four values:
- whether it is a BST,
- its smallest key,
- its largest key,
- the sum of its keys.
A node's subtree is a BST exactly when both children's subtrees are BSTs, the largest key on the left is less than the node's key, and the smallest key on the right is greater than it. When it is, its sum is left sum + right sum + node.val, its smallest key is the left side's smallest (or the node itself), and its largest key is the right side's largest (or the node itself). We compare the sum with the best answer so far.
Two details make this work:
- An empty subtree is a BST with smallest key
+infinityand largest key-infinity(a large sentinel such as2^30here), so a missing child never blocks the comparison. - Once a subtree is not a BST, no ancestor can be one either, so its other values no longer matter.
The answer starts at 0: if every key is negative, the best choice is the empty tree, as in Example 3. Strict comparisons also matter: a child equal to its parent breaks the BST.
Complexity: O(n) time, since every node is visited once, and O(h) extra space for the recursion, where h is the height of the tree.
class Solution:
def maxSumBST(self, root: Optional[TreeNode]) -> int:
INF = 1 << 30
best = 0 # the empty tree is a BST with sum 0, so the answer is never negative
# Returns (is_bst, smallest key, largest key, sum of keys) for the subtree.
def dfs(node: Optional[TreeNode]) -> Tuple[bool, int, int, int]:
nonlocal best
if node is None:
return True, INF, -INF, 0
left_bst, left_min, left_max, left_sum = dfs(node.left)
right_bst, right_min, right_max, right_sum = dfs(node.right)
if left_bst and right_bst and left_max < node.val < right_min:
total = left_sum + right_sum + node.val
best = max(best, total)
return True, min(left_min, node.val), max(right_max, node.val), total
return False, 0, 0, 0 # min/max/sum no longer matter: no ancestor can be a BST
dfs(root)
return best