333. Largest BST Subtree
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the size of the largest subtree in a given binary tree that is also a valid Binary Search Tree (BST). A subtree of a node includes the node itself and all of its descendants. The "largest" is defined by the number of nodes.
Solution
Largest BST Subtree in Python
# 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 largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
self.max_size = 0
self.postorder(root)
return self.max_size
def postorder(self, node: Optional[TreeNode]) -> tuple[int, float, float]:
"""
Returns a tuple: (size, lower_bound, upper_bound).
size = -1 indicates the subtree is not a BST.
size = 0 indicates a null node.
"""
if not node:
# For a null node, return size 0 and bounds that are always valid.
return (0, float('inf'), float('-inf'))
# Get info from left and right subtrees.
left_size, left_lower, left_upper = self.postorder(node.left)
right_size, right_lower, right_upper = self.postorder(node.right)
# Check if the current subtree is a BST.
if left_size != -1 and right_size != -1 and left_upper < node.val < right_lower:
size = 1 + left_size + right_size
self.max_size = max(self.max_size, size)
# Calculate bounds for the current BST.
lower = left_lower if node.left else node.val
upper = right_upper if node.right else node.val
return (size, lower, upper)
# If not a BST, propagate this with size = -1.
return (-1, 0, 0)
Largest BST Subtree in Java
/**
* 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;
* }
* }
*/
// A helper class to store information about a subtree.
class SubtreeInfo {
int size; // Size of the BST. -1 if not a BST, 0 for null.
long lower; // Minimum value in the BST subtree.
long upper; // Maximum value in the BST subtree.
public SubtreeInfo(int size, long lower, long upper) {
this.size = size;
this.lower = lower;
this.upper = upper;
}
}
class Solution {
private int maxSize = 0;
public int largestBSTSubtree(TreeNode root) {
postorder(root);
return maxSize;
}
private SubtreeInfo postorder(TreeNode node) {
// Base case: an empty tree is a BST of size 0.
if (node == null) {
// Use Long.MAX_VALUE/MIN_VALUE to handle node values at Integer boundaries.
return new SubtreeInfo(0, Long.MAX_VALUE, Long.MIN_VALUE);
}
// Recursively get info from left and right subtrees.
SubtreeInfo left = postorder(node.left);
SubtreeInfo right = postorder(node.right);
// Check if the current node can form a BST with its subtrees.
if (left.size != -1 && right.size != -1 && node.val > left.upper && node.val < right.lower) {
int size = 1 + left.size + right.size;
maxSize = Math.max(maxSize, size);
long newLower = node.left != null ? left.lower : node.val;
long newUpper = node.right != null ? right.upper : node.val;
return new SubtreeInfo(size, newLower, newUpper);
}
// If it's not a BST, propagate this info up by returning size -1.
return new SubtreeInfo(-1, 0, 0);
}
}
Largest BST Subtree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// A structure to hold information about a subtree.
struct Result {
int size; // Size of the BST. -1 if not a BST, 0 for null.
long lower; // Minimum value in the BST subtree.
long upper; // Maximum value in the BST subtree.
};
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
postorder(root);
return maxSize;
}
private:
int maxSize = 0;
Result postorder(TreeNode* node) {
// Base case: an empty tree is a BST of size 0.
if (!node) {
// Use LONG_MAX/MIN to handle node values at INT_MAX/MIN.
return {0, LONG_MAX, LONG_MIN};
}
// Recursively get info from left and right subtrees.
Result left = postorder(node->left);
Result right = postorder(node->right);
// Check if the current node can form a BST with its subtrees.
// A subtree is a BST if its left and right subtrees are BSTs
// and the current node's value is between the max of the left
// and the min of the right.
if (left.size != -1 && right.size != -1 && (long)node->val > left.upper && (long)node->val < right.lower) {
int size = 1 + left.size + right.size;
maxSize = std::max(maxSize, size);
// The new min value is the min of the left subtree (or current node's value if left is null).
long new_lower = node->left ? left.lower : node->val;
// The new max value is the max of the right subtree (or current node's value if right is null).
long new_upper = node->right ? right.upper : node->val;
return {size, new_lower, new_upper};
}
// If it's not a BST, propagate this info up by returning size -1.
return {-1, 0, 0};
}
};
Largest BST Subtree in TypeScript
/**
* 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 largestBSTSubtree(root: TreeNode | null): number {
let maxSize = 0;
/**
* @returns A tuple: [size, min_val, max_val]
* size = -1 if subtree is not a BST.
* size = 0 for a null node.
*/
function postorder(node: TreeNode | null): [number, number, number] {
if (!node) {
// For a null node, return size 0 and bounds that are always valid.
return [0, Infinity, -Infinity];
}
// Get info from left and right subtrees.
const [leftSize, leftMin, leftMax] = postorder(node.left);
const [rightSize, rightMin, rightMax] = postorder(node.right);
// Check if the current subtree is a BST.
if (leftSize !== -1 && rightSize !== -1 && node.val > leftMax && node.val < rightMin) {
const size = 1 + leftSize + rightSize;
maxSize = Math.max(maxSize, size);
// Calculate bounds for the current BST.
const minVal = node.left !== null ? leftMin : node.val;
const maxVal = node.right !== null ? rightMax : node.val;
return [size, minVal, maxVal];
}
// If not a BST, propagate this with size = -1.
return [-1, 0, 0];
}
postorder(root);
return maxSize;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.