Skip to content
Related Articles

Related Articles

Find the largest BST subtree in a given Binary Tree | Set 3

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 08 Aug, 2022

Largest BST in a Binary Tree | Set 3

Method 3 (Shorter, Smarter and More Efficient) 

In this section, a different O(n) solution is discussed. This solution is simpler than the solutions discussed in Set-1 and Set-2 and works in O(n) time. In this method, we do not need to check explicitly if the binary tree is BST. A Tree is BST if the following is true for every node x. 

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 will use a array/list ans :

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

Algorithm:

1. If root==None:
return INT_MAX,INT_MIN,0
2. If (root.left==None and root.right==None):
             return root.data,root.data,1
3. Initialize ans=[0,0,0]
4. Check if the largest value of the left subtree is less than the value of the root node and the smallest value of the right subtree is greater than the value of the root node, if this holds true, update the ans accordingly and return ans.
5. If 4 is false, we will assign values as IMIN,IMAX, max(left[2],right[2] and return ans.

C++




// C++ program to find largest BST in a Binary Tree.
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
      Node(int val)
    {
          this->data = val;
          left = NULL;
          right = NULL;
    }
};
 
vector<int> largestBSTBT(Node* root)
{
    // Base cases : When tree is empty or it has one child.
    if (root == NULL)
        return {INT_MAX, INT_MIN, 0};
    if (root->left == NULL && root->right == NULL)
        return {root->data, root->data, 1};
 
    // Recur for left subtree and right subtrees
    vector<int> left = largestBSTBT(root->left);
    vector<int> right = largestBSTBT(root->right);
 
    // Create a return variable and initialize its size.
    vector<int> ans(3, 0);
 
    // If whole tree rooted under current root is BST.
    if ((left[1] < root->data) && (right[0] > root->data))
    {
        ans[0] = min(left[0], min(right[0], root->data));
        ans[1] = max(right[1], max(left[1], root->data));
        // Update answer for tree rooted under current 'root'
        ans[2] = 1 + left[2] + right[2];
        return ans;
    }
 
    // If whole tree is not BST, return maximum of left and right subtrees
    ans[0] = INT_MIN;
    ans[1] = INT_MAX;
    ans[2] = max(left[2], right[2]);
 
    return ans;
}
 
int largestBSTBTutil(Node *root)
{
      return largestBSTBT(root)[2];
}
 
// Driver Function
int main() {
 
    /* Let us construct the following Tree
        50
       /  \
      75  45
     /
    45 */
 
    struct Node *root = new Node(50);
    root->left = new Node(75);
    root->right = new Node(45);
    root->left->left = new Node(40);
    printf(" Size of the largest BST is %d\n", largestBSTBTutil(root));
    return 0;
}
 
// This Code is cuntributed by Ajay Makvana

Python3




#User function Template for python3
IMIN = -2147483648
IMAX = 2147483647
def largestBst(root):
        if root==None:
            return IMAX,IMIN,0
        if (root.left==None and root.right==None):
            return root.data,root.data,1
         
        left=largestBst(root.left)
        right=largestBst(root.right)
 
         
        ans=[0,0,0]
         
        if left[1]<root.data and right[0]>root.data:
            ans[0]=min(left[0],right[0],root.data)
            ans[1]=max(right[1],left[1],root.data)
            ans[2]=1+left[2]+right[2]
            return ans
 
        ans[0]=IMIN
        ans[1]=IMAX
        ans[2]=max(left[2],right[2])
        return ans
 
def largestBstUtil(root):
      # Return the size of the largest sub-tree which is also a BST
     return largestBst(root)[2]
     
#  Driver Code Starts
import sys
sys.setrecursionlimit(1000000)
from collections import deque
# Tree Node
class newNode:
    def __init__(self, val):
        self.right = None
        self.data = val
        self.left = None
 
# Driver Code
if __name__ == '__main__':
      
    """Let us construct the following Tree
        50
        / \
        75 45
    /
    40 """
    root = newNode(50)
    root.left = newNode(75)
    root.right = newNode(45)
    root.left.left = newNode(40)
    print("Size of the largest BST is",largestBstUtil(root))

Output

Size of the largest BST is 2

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

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!