Check for BST | Practice | GeeksforGeeks

Given the root of a binary tree. Check whether it is a BST or not.
Note: We are considering that BSTs can not contain duplicate Nodes.
A BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.


The right subtree of a node contains only nodes with keys greater than the node's key.


Both the left and right subtrees must also be binary search trees.

 
Example 1:
Input:
   2
 /    \
1      3
Output: 1 
Explanation: 
The left subtree of root node contains node
with key lesser than the root nodes key and 
the right subtree of root node contains node 
with key greater than the root nodes key.
Hence, the tree is a BST.

Example 2:
Input:
  2
   \
    7
     \
      6
       \
        5
         \
          9
           \
            2
             \
              6
Output: 0 
Explanation: 
Since the node with value 7 has right subtree 
nodes with keys less than 7, this is not a BST.

Your Task:
You don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree as a parameter and returns true if the given binary tree is BST, else returns false. 
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
0 <= Number of edges <= 100000
0
anikethjain
This comment was deleted.
0
smohtashima15 hours ago
Simple Python Solution with Iterative DFS using STACK:
def isBST(self, root):
        #code here
        if not root:
            return True

        stack = [(root, -math.inf, math.inf)]
        while stack:
            root, lower, upper = stack.pop()
            if not root:
                continue
            val = root.data
            if val <= lower or val >= upper:
                return False
            stack.append((root.right, val, upper))
            stack.append((root.left, lower, val))
        return True
+1
shashwatsingh7116 hours ago
By Inorder Trav → Time - O(N)
Space - O(N)
 
 bool isValidBST(TreeNode* root) {                           if(!root->left && !root->right ) return true;             long prev=LONG_MIN;       stack<TreeNode*> st;              TreeNode* ptr=root;              while(!st.empty() || ptr)       {           if(ptr)           {               st.push(ptr);               ptr=ptr->left;           }           else           {               ptr=st.top();               st.pop();                              if(prev >= ptr->val) return false;               prev=ptr->val;               ptr=ptr->right;           }       }              return true;          }
 
By Morris Trav -→
Time = O(n)
Space = O(1)
 
 bool isBST(Node* root)    {       Node* ptr=root;       int prev=0;              while(ptr)       {           if(!ptr->left)           {               if(prev>ptr->data) return false;               prev=ptr->data;               ptr=ptr->right;           }           else           {               Node* temp = ptr->left;               while(temp->right && temp->right!=ptr) temp=temp->right;                              if(!temp->right)                {                   temp->right=ptr;                   ptr=ptr->left;               }                              else               {                   temp->right=NULL;                   if(prev>ptr->data) return false;                   prev=ptr->data;                   ptr=ptr->right;               }                          }       }       return true;          }
+1
sudhirdaga19981 day ago
bool isValidBST(Node *root,int mini,int maxi)   {       if(root==NULL)           return true;       if(root->data > maxi || root->data < mini)           return false;       return (isValidBST(root->left,mini,root->data) && isValidBST(root->right,root->data,maxi));   }     bool isBST(Node* root)    {       // Your code here       return isValidBST(root,INT_MIN,INT_MAX);   }
0
siddhantmedar2 days ago
    #Function to check whether a Binary Tree is BST or not.   def isBST(self, root):       #code here       def util(root, mn, mx):           if not root:               return True                      if root.data < mn or root.data > mx:               return False                          return util(root.left, mn, root.data-1) and util(root.right, root.data+1 ,mx)              return util(root, float("-inf"), float("inf"))       
0
neeshumaini554 days ago
	#intition
    #for every node we will define the range of values that 		  satify the condition
    #condition -- a < root.val < b
    #a -- min_value
    #b -- max_value
    def bst(self,root,int_min,int_max):
        if root is None:
            return True
        if root.data < int_min or root.data > int_max:
            return False
        return self.bst(root.left,int_min,root.data) and self.bst(root.right,root.data,int_max)
    def isBST(self, root):
        return self.bst(root,float('-inf'),float('inf'))
+1
anshrathore69844 days ago
bool isBST(Node* node)    {       if(node ==NULL)           return 1;                  if(node->left!=NULL && maxValue(node->left,node->data))           return 0;              if(node->right!=NULL && minValue(node->right,node->data))           return 0;                  if (!isBST(node->left) || !isBST(node->right))            return 0;                  return 1;        }   bool maxValue(Node* node,int i)   {       if(node->data > i)           return 1;       else           return 0;   }   bool minValue(Node* node , int i)   {       if(node->data < i)           return 1;       else           return 0;          }
 
101 test case passed
 
0
debojyotisinha5 days ago
Programming Language: Java
Test Cases Passed: 120 / 120
Total Time Taken: 0.39/1.13
 
public class Solution {
    int prev;

    boolean inOrder(Node root) {
        if (root != null) {
            boolean check1 = inOrder(root.left);
            
            if(prev <= root.data) {
                prev = root.data;
            } else {
                return false;
            }

            boolean check2 = inOrder(root.right);
            
            return check1 && check2;
        }
        
        return true;
    }
    
    boolean isBST(Node root) {
        prev = Integer.MIN_VALUE;
        
        return inOrder(root);
    }
}
-1
shubham211019975 days ago
class bst{
       boolean isbst;
       int max;
       int min;
   }
   public  bst isbst(Node root){
       if(root==null){
           bst bp= new bst();
           bp.isbst=true;
           bp.min=Integer.MAX_VALUE;
           bp.max=Integer.MIN_VALUE;
           return bp;
       }
       bst lp=isbst(root.left);
       bst rp=isbst(root.right);
       
       bst mp=new bst();
       mp.isbst=(root.data>=lp.max && root.data<=rp.min)&&lp.isbst && rp.isbst;
       
       mp.min=Math.min(root.data,Math.min(lp.min,rp.min));
       mp.max=Math.max(root.data,Math.max(lp.max,rp.max));
       return mp;
   }
   
   boolean isBST(Node root)
   {
       bst res=isbst(root);
       return res.isbst;
   }
0
kkumarakash70111 week ago
 bool bst(Node*root,int min,int max)   {       if(root==NULL)       return true;              if(root->data<min || root->data>max)       return false;              return bst(root->left,min,root->data)&&bst(root->right,root->data,max);   }   bool isBST(Node* root)    {       // Your code here       return bst(root,INT_MIN,INT_MAX);   }
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.