VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/

⇱ Largest BST Subtree - Simple Implementation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest BST Subtree - Simple Implementation

Last Updated : 23 Jul, 2025

Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size (number of nodes) of the whole tree.

Examples:

Input:

👁 Largest-BST-Subtree---Simple-Implementation-1

Output: 3
The following subtree is the
maximum size BST subtree

👁 Sorted-Linked-List-to-Balanced-BST


Input:

👁 Largest-BST-Subtree---Simple-Implementation-3


Output: 5
The following subtree is the
maximum size BST subtree

👁 Largest-BST-Subtree---Simple-Implementation-4_

Prerequisite : Validate BST (Minimum and Maximum Value Approach)

We have discussed Naive and Efficient Approaches in Largest BST in a Binary Tree . Here we are going to discuss a simpler implementation of the efficient solution that returns an array of size 3 instead of creating a separate class.

We use the below same idea

1. The largest value in the left subtree (of x) is smaller than the value of x.
2. The smallest value in the right subtree (of x) is greater than the value of x.

So, we will just check if the largest value of the left subtree is less than the value of the root node and the smallest value of right subtree is greater than the value of root node.

We use a array/list of size 3 :

• ans[0]=minimum value
• ans[1]=maximum value
• ans[2]=size of current largest BST


Output
2

Time Complexity: O(n),
 Auxiliary Space: O(n)

Here n is the number of nodes in the given Binary Tree.  

Comment