Open In App

Largest BST Subtree - Simple Implementation

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

C++14
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left;
    Node *right;
    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Returns a vector of size 3: {min, max, size of largest BST}
// Vector {INT_MAX, INT_MIN, 0} is returned for an empty tree
vector<int> largestBSTUtil(Node *root) {
    if (!root)
        return {INT_MAX, INT_MIN, 0};

    if (!root->left && !root->right)
        return {root->data, root->data, 1};

    vector<int> left = largestBSTUtil(root->left);
    vector<int> right = largestBSTUtil(root->right);

    vector<int> ans(3);

    // If the current subtree rooted at root is a BST
    if (left[1] < root->data && right[0] > root->data) {
        ans[0] = min(left[0], root->data);   
        ans[1] = max(right[1], root->data); 
        ans[2] = left[2] + right[2] + 1;     
        return ans;
    }

    // If the subtree is not a BST
    ans[0] = INT_MIN;
    ans[1] = INT_MAX;
    ans[2] = max(left[2], right[2]); 

    return ans;
}

// Function to find the size of the largest BST
// in a binary tree
int largestBst(Node *root) {
    return largestBSTUtil(root)[2];
}

int main() {
    Node *root = new Node(50);
    root->left = new Node(75);
    root->right = new Node(45);
    root->left->left = new Node(40);
    cout << largestBst(root) << endl;
    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

public class GfG {

    // Returns an array of size 3: {min, max, size of largest BST}
    // Array {Integer.MAX_VALUE, Integer.MIN_VALUE, 0} is 
    // returned for an empty tree
    public static int[] largestBSTUtil(Node root) {
        if (root == null) {
            return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
        }

        if (root.left == null && root.right == null) {
            return new int[]{root.data, root.data, 1};
        }

        int[] left = largestBSTUtil(root.left);
        int[] right = largestBSTUtil(root.right);

        int[] ans = new int[3];

        // If the current subtree rooted at root is a BST
        if (left[1] < root.data && right[0] > root.data) {
            ans[0] = Math.min(left[0], root.data);  
            ans[1] = Math.max(right[1], root.data);
            ans[2] = left[2] + right[2] + 1;    
            return ans;
        }

        // If the subtree is not a BST
        ans[0] = Integer.MIN_VALUE;
        ans[1] = Integer.MAX_VALUE;
        ans[2] = Math.max(left[2], right[2]);

        return ans;
    }

    // Function to find the size of the largest BST
    // in a binary tree
    public static int largestBst(Node root) {
        return largestBSTUtil(root)[2];
    }

    public static void main(String[] args) {
        Node root = new Node(50);
        root.left = new Node(75);
        root.right = new Node(45);
        root.left.left = new Node(40);
        System.out.println(largestBst(root));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Returns a list of size 3: [min, max, size of largest BST]
# List [float('inf'), float('-inf'), 0] is returned for an empty tree
def largestBSTUtil(root):
    if not root:
        return [float('inf'), float('-inf'), 0]

    if not root.left and not root.right:
        return [root.data, root.data, 1]

    left = largestBSTUtil(root.left)
    right = largestBSTUtil(root.right)

    ans = [0, 0, 0]

    # If the current subtree rooted at root is a BST
    if left[1] < root.data < right[0]:
        ans[0] = min(left[0], root.data)  
        ans[1] = max(right[1], root.data)
        ans[2] = left[2] + right[2] + 1  
        return ans

    # If the subtree is not a BST
    ans[0] = float('-inf')
    ans[1] = float('inf')
    ans[2] = max(left[2], right[2])  

    return ans

# Function to find the size of the largest BST in a binary tree
def largestBst(root):
    return largestBSTUtil(root)[2]

# Driver program to test the above functions
if __name__ == "__main__":
    root = Node(50)
    root.left = Node(75)
    root.right = Node(45)
    root.left.left = Node(40)
    
    print(largestBst(root))
C#
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class Program {
    // Returns an array of size 3: [min, max, size of largest BST]
    // Array {int.MaxValue, int.MinValue, 0} is returned for an empty tree
    public static int[] largestBSTUtil(Node root) {
        if (root == null)
            return new int[] { int.MaxValue, int.MinValue, 0 };

        if (root.left == null && root.right == null)
            return new int[] { root.data, root.data, 1 };

        int[] left = largestBSTUtil(root.left);
        int[] right = largestBSTUtil(root.right);

        int[] ans = new int[3];

        // If the current subtree rooted at root is a BST
        if (left[1] < root.data && root.data < right[0]) {
            ans[0] = Math.Min(left[0], root.data);  
            ans[1] = Math.Max(right[1], root.data); 
            ans[2] = left[2] + right[2] + 1;        
            return ans;
        }

        // If the subtree is not a BST
        ans[0] = int.MinValue;
        ans[1] = int.MaxValue;
        ans[2] = Math.Max(left[2], right[2]); 

        return ans;
    }

    // Function to find the size of the largest BST in a binary tree
    public static int largestBst(Node root) {
        return largestBSTUtil(root)[2];
    }

    // Driver program to test the above functions
    public static void Main() {
        Node root = new Node(50);
        root.left = new Node(75);
        root.right = new Node(45);
        root.left.left = new Node(40);

        Console.WriteLine(largestBst(root));  // Output: 1
    }
}
JavaScript
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Returns an array of size 3: [min, max, size of largest BST]
// Array [Infinity, -Infinity, 0] is returned for an empty tree
function largestBSTUtil(root) {
    if (!root) {
        return [Infinity, -Infinity, 0];
    }

    if (!root.left && !root.right) {
        return [root.data, root.data, 1];
    }

    let left = largestBSTUtil(root.left);
    let right = largestBSTUtil(root.right);

    let ans = [0, 0, 0];

    // If the current subtree rooted at root is a BST
    if (left[1] < root.data && root.data < right[0]) {
        ans[0] = Math.min(left[0], root.data);  
        ans[1] = Math.max(right[1], root.data);  
        ans[2] = left[2] + right[2] + 1;        
        return ans;
    }

    // If the subtree is not a BST
    ans[0] = -Infinity;
    ans[1] = Infinity;
    ans[2] = Math.max(left[2], right[2]);  
    return ans;
}

// Function to find the size of the largest BST in a binary tree
function largestBst(root) {
    return largestBSTUtil(root)[2];
}

// Driver program to test the above functions
let root = new Node(50);
root.left = new Node(75);
root.right = new Node(45);
root.left.left = new Node(40);

console.log(largestBst(root));  // Output: 1

Output
2

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

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


Similar Reads