Largest BST | Practice | GeeksforGeeks

Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
        1
      /   \
     4     4
   /   \
  6     8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.

Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
            6
        /       \
       6         3
        \      /   \
         2    9     3
          \  /  \
          8 8    2 
Output: 2
Explanation: The following sub-tree is a
BST of size 2: 
       2
    /    \ 
   N      8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree. 
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 106
0
spideyyy1091 week ago
c++ code ,using DP on Trees concept
bool isBST(Node * root,int mini, int maxi){
       if(!root) return true;
       if(root->data <= mini || root->data >= maxi) return false;
       return isBST(root->left,mini,root->data)&&isBST(root->right,root->data,maxi);
   }
   
    int max_size = INT_MIN; //declared globally
   int maxsumDPonTrees(Node * root ){
       
       if(!root) return 0;
       int l = maxsumDPonTrees(root->left);
       int r=  maxsumDPonTrees(root->right);
       int temp = l+r+1;
       max_size = max(max_size , temp);
       return temp; 
   }
   
   void helper(Node * root){
     
       if(!root) return;
       //if i have a BST then  i will get the maxsize using DP on trees
       if(isBST(root,INT_MIN,INT_MAX)) 
          maxsumDPonTrees(root);
       else{ //if its not a BST then we still have to check for left and the right subtrees
         helper(root->left);
         helper(root->right);
       }
   }
   /*You are required to complete this method */
   // Return the size of the largest sub-tree which is also a BST
   int largestBst(Node *root)
   {
    //Your code here
    max_size = 0;
    helper(root);
    return max_size;
   }
0
arbaazmakandar981 week ago
class info{   public:   int mini;   int maxi;   bool isBST;   int size;};info solve(Node* root, int &ans){      //base case   if(!root){       return {INT_MIN, INT_MAX, true, 0};   }   info left = solve(root->left, ans);   info right = solve(root->right, ans);      info currNode;      currNode.size = left.size + right.size + 1;   currNode.maxi = max(root->data, right.maxi);   currNode.mini = min(root->data, left.mini);      if(left.isBST && right.isBST && (root->data > left.maxi && root->data < right.mini)){       currNode.isBST = true;        ans = max(ans, currNode.size);   }   else{       currNode.isBST = false;   }      //update ans   // if(currNode.isBST){         // }      return currNode;}
class Solution{   public:     /*You are required to complete this method */   // Return the size of the largest sub-tree which is also a BST   int largestBst(Node *root)   {    //Your code here    int ans = 0;    info temp = solve(root, ans);    return ans;       }};
 
 
//WHY MY CODE IS NOT WORKING?????
//please help
+1
800dheerajmaurya2 weeks ago
Easiest approach:
Recur form bottom to top, so that you can give info to the parent node whether the left and right subtree is a BST or not.Make a class/struct of 4 members i.e. size(your final answer), min(minimum value in that subtree), max(maximum value in that subtree), isBST(whether this subtree is BST or not).If the left and right child is BST and value of current node is greater than the maximum value of left subtree and is less than the minimum value of the right subtree then, the node and left subtree and right subtree comparises a whole new BST. Now update the max size.Refer to the following code.Thanks. :)
Recur form bottom to top, so that you can give info to the parent node whether the left and right subtree is a BST or not.
Make a class/struct of 4 members i.e. size(your final answer), min(minimum value in that subtree), max(maximum value in that subtree), isBST(whether this subtree is BST or not).
If the left and right child is BST and value of current node is greater than the maximum value of left subtree and is less than the minimum value of the right subtree then, the node and left subtree and right subtree comparises a whole new BST. Now update the max size.
Refer to the following code.
Thanks. :)
 
class quad{   public:   int size;   int min;   int max;   bool isBST;};
 
quad check(Node* root){   if(root==NULL)       return {0,INT_MAX,INT_MIN,true};   quad x=check(root->left);   quad y=check(root->right);   if(root->data>x.max&&root->data<y.min&&x.isBST&&y.isBST)       return {x.size+y.size+1,min(root->data,x.min),max(root->data,y.max),true};   return {max(x.size,y.size),min(root->data,x.min),max(root->data,y.max),false};}
 
class Solution{   public:   int largestBst(Node *root)   {    return check(root).size;   }};
0
amishasahu3282 weeks ago
class NodeValue
{
    public: int maxSize, maxValue, minValue;
    public:
    NodeValue(int minValue, int maxValue, int maxSize)
    {
        this->minValue = minValue;
        this->maxValue = maxValue;
        this->maxSize = maxSize;
    }
};
class Solution{
    private:
    NodeValue largestBSTHelper(Node *root)
    {
        // An empty tree is a BST of size 0.
        // maxValue to be the extream small
        // minValue to be the extream larger
        // To make it comparable
        if(!root)
            return NodeValue(INT_MAX, INT_MIN, 0);
        
        // Get values from left and right subtree of current tree.
        auto left = largestBSTHelper(root->left);
        auto right = largestBSTHelper(root->right);
        
        // Current node is greater than max value in left AND smaller than min value in right, it is a BST.
        if(left.maxValue < root->data && root->data < right.minValue)
        {
            return NodeValue(min(root->data, left.minValue), max(root->data, right.maxValue), left.maxSize + right.maxSize + 1);
        }
        // Otherwise, return [-inf, inf] so that parent can't be valid BST
        return NodeValue(INT_MIN, INT_MAX, max(left.maxSize, right.maxSize));
    }
    public:
    /*You are required to complete this method */
    // Return the size of the largest sub-tree which is also a BST
    int largestBst(Node *root)
    {
    	//Your code here
    	return largestBSTHelper(root).maxSize;
    }
};
0
nitansshujain
This comment was deleted.
+2
raghavbansal44 weeks ago
Easy JAVA Solution, TC - O(N) , SC - O(1)
class newNode{
        int size;
        int min;
        int max;
    }
class Solution{
    
    // Return the size of the largest sub-tree which is also a BST
    
    static newNode getSize(Node node){
            if(node == null){
                newNode a = new newNode();
                a.size = 0;
                a.min = Integer.MAX_VALUE;
                a.max = Integer.MIN_VALUE;
                return a;
            }
            
            newNode np = new newNode();
            newNode l = getSize(node.left);
            newNode r = getSize(node.right);
            
            if(l.max < node.data && node.data < r.min){
                np.size = l.size + r.size + 1;
                np.min = Math.min(node.data,l.min);
                np.max = Math.max(node.data,r.max);
            }
            else{
                np.size = Math.max(l.size,r.size);
                np.min = Integer.MIN_VALUE;
                np.max = Integer.MAX_VALUE;
            }
            return np;
        }
    static int largestBst(Node root)
    {
        return getSize(root).size;
        
    }
    
}
+1
sandeep55211 month ago
C++ O(n) post-order Solution (0.0 time Taken)
pair<pair<int,int>,int> func(Node *root){
       if(!root) return {{0,INT_MIN},INT_MAX};
       if(!(root->left) and !(root->right)) return {{1,root->data},root->data};
       auto a=func(root->left);
       auto b=func(root->right);
       if(a.first.second<root->data and b.second>root->data)
           return {{1+a.first.first+b.first.first,max(root->data,b.first.second)},min(root->data,a.second)};
       return {{max(a.first.first,b.first.first),INT_MAX},INT_MIN};
   }   
   int largestBst(Node *root)
   {
       auto c=func(root);
       return c.first.first;
    //Your code here
   } 
0
abrajput15061 month ago
void helper(Node* root,vector<int> &v){
        if(!root)
            return;
        helper(root->left,v);
        v.push_back(root->data);
        helper(root->right,v);
    }
    bool isBST(Node* root){
        vector<int> v;
        helper(root,v);
        for(int i = 1;i<v.size();i++){
            if(v[i]<=v[i-1])
                return false;
        }
        return true;
    }
    int noOfnodes(Node* root){
        if(!root)
            return 0;
        return 1+noOfnodes(root->left)+noOfnodes(root->right);
    }
    int largestBst(Node *root)
    {
    	//Your code here
    	if(!root)
    	    return 0;
    	if(isBST(root))
    	    return noOfnodes(root);
	    return max(largestBst(root->left),largestBst(root->right));
    }
0
terusrihitha9871 month ago
//INORDER APPROACH
 
void solve1(Node*temp,vector<int>&v,int &cnt){   if(temp==NULL)   return;   solve1(temp->left,v,cnt);   v.push_back(temp->data);   cnt++;   solve1(temp->right,v,cnt);}int maxi=INT_MIN;void solve(Node *root){   if(root==NULL)   return;   else   {      vector<int>v;      int cnt=0;       solve1(root,v,cnt);           int flag=0;           for(int j=1;j<v.size();j++)           {               if(v[j]<=v[j-1])               {                   flag=1;                   break;               }           }           if(flag==0)           {             maxi=max(maxi,cnt);           }           v.clear();                     solve(root->left);       solve(root->right);   }}   int largestBst(Node *root)   {        solve(root);    return maxi;   }
 
 
0
kambojabhishek0611 month ago
// here  anyone clear me why its not given a correct output
class Solution{       class NodeValue{       public int minNode,maxNode,maxsize;              NodeValue(int mixNode,int maxNode,int maxsize){           this.minNode=maxNode;           this.maxNode=minNode;           this.maxsize=maxsize;       }   }   // Return the size of the largest sub-tree which is also a BST   public NodeValue solve(Node root){       if(root==null) {           return new NodeValue(Integer.MAX_VALUE,Integer.MIN_VALUE,0);       }       NodeValue left=solve(root.left);       NodeValue right=solve(root.right);              if(left.maxNode<root.data&&right.minNode>root.data){        return new NodeValue(Math.min(left.minNode,root.data),Math.max(right.maxNode,root.data),1+left.maxsize+right.maxsize);       }       else return new NodeValue(Integer.MIN_VALUE,Integer.MAX_VALUE,Math.max(left.maxsize,right.maxsize));   }   public int largestBst(Node root)   {       // Write your code here       return solve(root).maxsize;       //if(NodeValue max.size==0) return 1;          }   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.