Given the root of a binary tree, find the largest subtree that is also a Binary Search Tree (BST).

The largest means the subtree with the maximum number of nodes.

A Binary Search Tree (BST) is a tree where:

  • The left subtree values are less than the parent node's value
  • The right subtree values are greater than the parent node's value

Note: A subtree must include all of its descendants.

Input & Output

Example 1 — Mixed Valid/Invalid BST
$ Input: root = [10,5,15,1,8,null,7]
Output: 3
💡 Note: The left subtree [5,1,8] is a valid BST with 3 nodes. The right subtree [15,7] is invalid because 7 < 15. The whole tree is also invalid BST, so the largest BST subtree has 3 nodes.
Example 2 — Entire Tree is BST
$ Input: root = [4,2,6,1,3,5,7]
Output: 7
💡 Note: The entire tree is a valid BST: left subtree values (1,2,3) < root (4) < right subtree values (5,6,7). All 7 nodes form the largest BST subtree.
Example 3 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: A single node is always a valid BST, so the largest BST subtree has 1 node.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -104 ≤ Node.val ≤ 104

Visualization

Tap to expand
Largest BST Subtree Problem Overview10515187✓ Valid BST SubtreeSize: 3 nodes (1 < 5 < 8)✗ Invalid BST7 < 15 violates BST propertyAnswer: 3 (largest valid BST subtree)
Understanding the Visualization
1
Input Tree
Binary tree with mixed valid/invalid BST subtrees
2
Validate Subtrees
Check BST property for each subtree using post-order traversal
3
Find Maximum
Return size of largest valid BST subtree found
Key Takeaway
🎯 Key Insight: Use post-order traversal to validate BST properties bottom-up while tracking subtree sizes efficiently
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 12
127.6K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen