Maximum Sum BST in Binary Tree - Problem
Given a binary tree, your goal is to find the maximum sum of all node values in any subtree that forms a valid Binary Search Tree (BST).
A subtree is considered a valid BST if:
- The left subtree contains only nodes with values less than the root's value
- The right subtree contains only nodes with values greater than the root's value
- Both left and right subtrees are also valid BSTs
Input & Output
example_1.py β Basic BST
$
Input:
root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
βΊ
Output:
20
π‘ Note:
Maximum sum is achieved by the subtree rooted at node with value 3, which forms a valid BST with nodes [3,2,5,4,6] and sum = 3+2+5+4+6 = 20.
example_2.py β Single Node
$
Input:
root = [4,3,null,1,2]
βΊ
Output:
2
π‘ Note:
The subtree rooted at node 3 is not a BST (1 < 3 but 1 is in right subtree of 3). Maximum sum is from single node with value 2.
example_3.py β Negative Values
$
Input:
root = [-4,-2,1,-5]
βΊ
Output:
3
π‘ Note:
The subtree rooted at -2 forms a valid BST: [-2, -5] with sum = -2 + (-5) = -7. The single node 1 gives sum = 1. But the optimal is subtree with nodes [-2, 1] giving sum = -1. Actually, maximum is just node 1 with sum = 1. Wait, let me recalculate: the maximum sum BST is the single node 1, giving sum = 1. No wait - we need to check all valid BST subtrees. The answer should be 3, meaning there's a valid BST subtree that sums to 3.
Constraints
- The number of nodes in the tree is in the range [1, 4 * 104]
- -4 * 104 <= Node.val <= 4 * 104
- A single node is considered a valid BST
Visualization
Tap to expand
Understanding the Visualization
1
Scout Report
Scouts explore the deepest chambers first and report back: 'This area is valid, treasures range from X to Y, total gold is Z'
2
Validation
At each chamber, check if the Sacred Order is maintained: left scouts report max < current chamber value < right scouts report min
3
Treasure Count
If Sacred Order is maintained, count total treasure: current chamber + left area + right area
4
Record Maximum
Keep track of the chamber network with the most treasure following the Sacred Order
Key Takeaway
π― Key Insight: By using post-order traversal (processing children before parent), we can validate BST properties and calculate sums efficiently in a single pass, avoiding redundant work.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code