Given a binary treeroot, 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 * 104].
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Tree
Example 1
[1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Example 2
[4,3,null,1,2]
Example 3
[-4,-2,-5]
Step 02
Core Insight
What unlocks the optimal approach
Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minRight).
In each node compute theses parameters, following the conditions of a Binary Search Tree.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1373: Maximum Sum BST in Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans;
private final int inf = 1 << 30;
public int maxSumBST(TreeNode root) {
dfs(root);
return ans;
}
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[] {1, inf, -inf, 0};
}
var l = dfs(root.left);
var r = dfs(root.right);
int v = root.val;
if (l[0] == 1 && r[0] == 1 && l[2] < v && r[1] > v) {
int s = v + l[3] + r[3];
ans = Math.max(ans, s);
return new int[] {1, Math.min(l[1], v), Math.max(r[2], v), s};
}
return new int[4];
}
}
// Accepted solution for LeetCode #1373: Maximum Sum BST in Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxSumBST(root *TreeNode) (ans int) {
const inf = 1 << 30
var dfs func(root *TreeNode) [4]int
dfs = func(root *TreeNode) [4]int {
if root == nil {
return [4]int{1, inf, -inf, 0}
}
l, r := dfs(root.Left), dfs(root.Right)
if l[0] == 1 && r[0] == 1 && l[2] < root.Val && root.Val < r[1] {
s := l[3] + r[3] + root.Val
ans = max(ans, s)
return [4]int{1, min(l[1], root.Val), max(r[2], root.Val), s}
}
return [4]int{}
}
dfs(root)
return
}
# Accepted solution for LeetCode #1373: Maximum Sum BST in Binary Tree
# Definition for a binary tree node.
# 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: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> tuple:
if root is None:
return 1, inf, -inf, 0
lbst, lmi, lmx, ls = dfs(root.left)
rbst, rmi, rmx, rs = dfs(root.right)
if lbst and rbst and lmx < root.val < rmi:
nonlocal ans
s = ls + rs + root.val
ans = max(ans, s)
return 1, min(lmi, root.val), max(rmx, root.val), s
return 0, 0, 0, 0
ans = 0
dfs(root)
return ans
// Accepted solution for LeetCode #1373: Maximum Sum BST in Binary Tree
/**
* [1373] 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png" style="width: 320px; height: 250px;" />
*
* 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png" style="width: 134px; height: 180px;" />
*
* 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
*
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
// problem: https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/
// discuss: https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
// Credit: https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/solutions/791596/rust-translated-28ms-10-5m-100/
#[derive(Debug, Clone)]
pub struct Status {
is_bst: bool,
sum: i32,
max_left: i32,
min_right: i32,
}
impl Solution {
pub fn max_sum_bst(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut v = vec![];
Self::dfs_helper(&root, &mut v);
v.iter().fold(0, |acc, &x| if x > acc { x } else { acc })
}
fn dfs_helper(root: &Option<Rc<RefCell<TreeNode>>>, v: &mut Vec<i32>) -> Status {
match root {
None => Status {
is_bst: true,
sum: 0,
max_left: std::i32::MIN,
min_right: std::i32::MAX,
},
Some(node) => {
let node = node.borrow();
let left = Self::dfs_helper(&node.left, v);
let right = Self::dfs_helper(&node.right, v);
let val = node.val;
let s = if val > left.max_left && val < right.min_right {
Status {
is_bst: left.is_bst && right.is_bst,
sum: val + left.sum + right.sum,
max_left: val.max(right.max_left),
min_right: val.min(left.min_right),
}
} else {
Status {
is_bst: false,
sum: 0,
max_left: std::i32::MIN,
min_right: std::i32::MAX,
}
};
if s.is_bst {
v.push(s.sum)
}
s
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1373_example_1() {
let root = tree![
1, 4, 3, 2, 4, 2, 5, null, null, null, null, null, null, 4, 6
];
let result = 20;
assert_eq!(Solution::max_sum_bst(root), result);
}
#[test]
fn test_1373_example_2() {
let root = tree![4, 3, null, 1, 2];
let result = 2;
assert_eq!(Solution::max_sum_bst(root), result);
}
#[test]
fn test_1373_example_3() {
let root = tree![-4, -2, -5];
let result = 0;
assert_eq!(Solution::max_sum_bst(root), result);
}
}
// Accepted solution for LeetCode #1373: Maximum Sum BST in Binary Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function maxSumBST(root: TreeNode | null): number {
const inf = 1 << 30;
let ans = 0;
const dfs = (root: TreeNode | null): [boolean, number, number, number] => {
if (!root) {
return [true, inf, -inf, 0];
}
const [lbst, lmi, lmx, ls] = dfs(root.left);
const [rbst, rmi, rmx, rs] = dfs(root.right);
if (lbst && rbst && lmx < root.val && root.val < rmi) {
const s = ls + rs + root.val;
ans = Math.max(ans, s);
return [true, Math.min(lmi, root.val), Math.max(rmx, root.val), s];
}
return [false, 0, 0, 0];
};
dfs(root);
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.