Largest BST Subtree - Problem
You're given the root of a binary tree, and your mission is to find the largest subtree that is also a valid Binary Search Tree (BST).
But what makes this challenging? The "largest" means the subtree with the maximum number of nodes, and a subtree must include all of its descendants - you can't cherry-pick nodes!
BST Properties Reminder:
- All nodes in the left subtree have values
<root's value - All nodes in the right subtree have values
>root's value - Both left and right subtrees are also BSTs
Goal: Return the size (number of nodes) of the largest valid BST subtree.
Example: In a tree like [10, 5, 15, 1, 8, null, 7], you need to identify which portions form valid BSTs and find the one with the most nodes.
Input & Output
example_1.py โ Mixed BST Tree
$
Input:
root = [10,5,15,1,8,null,7]
โบ
Output:
3
๐ก Note:
The largest BST subtree is the one rooted at node 5, which includes nodes {5, 1, 8}. This subtree follows BST properties: 1 < 5 < 8. The right subtree rooted at 15 is invalid because 7 < 15 violates BST property.
example_2.py โ Single Node Tree
$
Input:
root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]
โบ
Output:
2
๐ก Note:
The largest BST subtree has 2 nodes. Multiple subtrees of size 2 exist: {2,3} and others. The entire tree is not a BST due to duplicate values and structure violations.
example_3.py โ Complete BST Tree
$
Input:
root = [2,1,3]
โบ
Output:
3
๐ก Note:
The entire tree is a valid BST since 1 < 2 < 3. Therefore, the largest BST subtree is the whole tree with 3 nodes.
Constraints
- The number of nodes in the tree is in the range [0, 104]
- -104 โค Node.val โค 104
- A subtree must include all of its descendants
Visualization
Tap to expand
Understanding the Visualization
1
Start from the bottom floors
Begin inspection at leaf nodes (individual rooms) - each is automatically valid
2
Check floor connections
For each floor, verify that left wing rooms < center room < right wing rooms
3
Gather section information
Collect data: smallest room number, largest room number, total rooms, validity status
4
Report to upper management
Pass summary information upward so upper floors can make decisions efficiently
5
Track largest valid section
Keep record of the biggest properly organized section found during inspection
Key Takeaway
๐ฏ Key Insight: Bottom-up information gathering allows us to make BST validity decisions efficiently by passing (min, max, size, isBST) data from children to parents, avoiding redundant validations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code