Leetcode #333: Largest BST Subtree
In this guide, we solve Leetcode #333 Largest BST Subtree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes. A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties: The left subtree values are less than the value of their parent (root) node's value.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Depth-First Search, Binary Search Tree, Dynamic Programming, Binary Tree
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: root = [10,5,15,1,8,null,7]
Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
Python Solution
# 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:
def dfs(root):
if root is None:
return inf, -inf, 0
lmi, lmx, ln = dfs(root.left)
rmi, rmx, rn = dfs(root.right)
nonlocal ans
if lmx < root.val < rmi:
ans = max(ans, ln + rn + 1)
return min(lmi, root.val), max(rmx, root.val), ln + rn + 1
return -inf, inf, 0
ans = 0
dfs(root)
return ans
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.