The Largest BST Subtree problem asks you to find the size of the largest subtree that is also a valid Binary Search Tree (BST). A subtree of a tree is a tree consisting of a node in and all of its descendants. A valid BST is defined by the property that for every node, all values in its left subtree are strictly smaller, and all values in its right subtree are strictly larger. The goal is to return the number of nodes in the largest such subtree.
This is a classic Binary Search Tree, Depth-First Search interview pattern question often seen at Microsoft and Meta. It's designed to test a candidate's ability to perform "bottom-up" tree traversal. A naive approach would be to check if each node is the root of a BST, which requires multiple passes over the tree. The optimized solution requires passing multiple pieces of information up the recursion stack, testing a candidate's mastery of recursion and state management.
The most efficient approach uses Depth-First Search (DFS) with Post-order Traversal. To determine if a node's tree is a BST, we need information from its children:
By returning a tuple or object containing these five values, a parent node can decide in if it forms a larger BST with its children. If node.val > left_max and node.val < right_min, and both children are BSTs, then the current node is also a BST of size left_size + right_size + 1.
Consider a tree:
10
/ \
5 15
/ \ \
1 8 7
5 > 1 (left max) and 5 < 8 (right min). Both children are BSTs. So, node 5 is a BST of size .15 < 7 is false. So, node 15 is NOT a BST.isBST(node) for every node, leading to complexity.Master post-order traversal for tree problems where the answer for a node depends on its children's properties. Practice problems like "Validate Binary Search Tree" and "Maximum Path Sum" to get comfortable with passing complex state up a recursive call stack.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Sum BST in Binary Tree | Hard | Solve | |
| Convert BST to Greater Tree | Medium | Solve | |
| Longest ZigZag Path in a Binary Tree | Medium | Solve | |
| Recover Binary Search Tree | Medium | Solve | |
| Inorder Successor in BST | Medium | Solve |