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 - Optimized DFS INPUT Binary Tree Structure 10 5 15 1 8 7 Valid BST subtree Invalid (7 < 15, wrong side) root = [10,5,15,1,8,null,7] Level-order representation ALGORITHM STEPS 1 Post-order DFS Process children before parent 2 Track at each node: isBST, size, min, max values 3 Validate BST property left.max < node < right.min 4 Update max size Track largest valid BST found DFS Processing Order: node(1): BST, size=1, [1,1] node(8): BST, size=1, [8,8] node(5): BST, size=3, [1,8] node(7): BST, size=1, [7,7] node(15): NOT BST (7<15) node(10): NOT BST FINAL RESULT Largest BST Subtree 5 1 8 Root: 5 Output: 3 Subtree with root=5 has 3 nodes and is a valid BST OK Key Insight: Use post-order traversal to collect info from children first. At each node, return (isBST, size, min, max). A subtree is BST if: both children are BST AND left.max < node.val < right.min. Time: O(n), Space: O(h). TutorialsPoint - Largest BST Subtree | Optimized DFS - Single Pass
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