Problem
Section titled “Problem”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: 20Explanation: 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: 2Explanation: 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: 0Explanation: All values are negatives. Return an empty BST.Constraints:
- The number of nodes in the tree is in the range .
-
Node.val
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”A subtree rooted at node is a BST exactly when
- both child subtrees are BSTs, and
node->valis 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 ().
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.
Algorithm
Section titled “Algorithm”dfs(node)returns anInfo {isBST, mn, mx, sum}for the subtree.- For
nullptr, return{true, INT_MAX, INT_MIN, 0}. - Compute
L = dfs(node->left)andR = dfs(node->right). - If
L.isBST && R.isBST && L.mx < node->val && node->val < R.mn, the subtree is a BST: its sum isL.sum + R.sum + node->val; updatebest; return{true, min(L.mn, node->val), max(R.mx, node->val), sum}. - Otherwise return
{false, ...}— the other fields no longer matter, because no ancestor can be a BST either. maxSumBSTcallsdfs(root)and returnsbest.
Walkthrough
Section titled “Walkthrough”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:
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.
Complexity
Section titled “Complexity”- Time: — each node is visited once with work.
- Space: — recursion stack, where
his the tree height ( for a skewed tree).
Edge cases
Section titled “Edge cases”- All values negative (Example 3): every BST sum is negative, so
beststays0(the empty BST). - Duplicate keys, e.g.
4with a left child4: the strict checksL.mx < node->valandnode->val < R.mnreject them, as the definition requires. - Sentinels: keys lie in , so
INT_MAX/INT_MINcan never collide with a real key, and the largest sum fits in anint.
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 bestGive it a try first
Attempt the problem on LeetCode — the code will still be here.
