Binary Search Tree

Check for Binary Search Tree

If you don’t know about tree or how to create a tree in python then you can visit here. In this post, we will check whether the given tree is a binary search tree or not.

Binary Search Tree

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.
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

Simple Approach

Python Code


    #Function to check whether a Binary Tree is BST or not.
    def isBST(self, root):
        #code here
        ele = (self.check_BST(root))
        for i in range (1,len(ele)):
            if(ele[i-1] > ele[i]):
                return False
        return True
        
    def check_BST(self,root):        
        elements =[]
        if root.left:
            # print(root.left.data ," L " , root.data)
            # if root.left.data > root.data:
            #     print(False)
            #     return False
            # else:
            elements += self.check_BST(root.left)
         
        elements.append(root.data)
        if root.right:
            # print(root.right.data  ," R " ,root.data)
            # if root.right.data < root.data: # print(False) # return False # else: elements += self.check_BST(root.right) return elements #{ # Driver Code Starts #Initial Template for Python 3 from collections import deque # Tree Node class Node: def __init__(self, val): self.right = None self.data = val self.left = None # Function to Build Tree def buildTree(s): #Corner Case if(len(s)==0 or s[0]=="N"): return None # Creating list of strings from input # string after spliting by space ip=list(map(str,s.split())) # Create the root of the tree root=Node(int(ip[0])) size=0 q=deque() # Push the root to the queue q.append(root) size=size+1 # Starting from the second element i=1 while(size>0 and i<len(ip)): #="" get="" and="" remove="" the="" front="" of="" queue="" currnode="q[0]" q.popleft()="" size="size-1" current="" node's="" value="" from="" string="" currval="ip[i]" if="" left="" child="" is="" not="" null="" if(currval!="N" ):="" create="" for="" node="" currnode.left="Node(int(currVal))" push="" it="" to="" q.append(currnode.left)="" right="" i="i+1" if(i="">=len(ip)):
            break
        currVal=ip[i]
        
        # If the right child is not null
        if(currVal!="N"):
            
            # Create the right child for the current node
            currNode.right=Node(int(currVal))
            
            # Push it to the queue
            q.append(currNode.right)
            size=size+1
        i=i+1
    return root
    
 </len(ip)):>

Space Optimized Answer

Python Code

 
    
    INT_MAX = 4294967296
    INT_MIN = -4294967296
    
    #Function to check whether a Binary Tree is BST or not.
    def isBST(self,node): 
        return (self.isBSTUtil(node, self.INT_MIN, self.INT_MAX)) 
      
    def isBSTUtil(self,node, mini, maxi): 
          
        #an empty tree is BST so we return true.
        if node is None: 
            return True
      
        #returning false if this node violates the min/max constraint.
        if node.data < mini or node.data > maxi: 
            return False
      
        #otherwise checking the subtrees recursively.
        #tightening the min or max constraint.
        return (self.isBSTUtil(node.left, mini, node.data -1) and
              self.isBSTUtil(node.right, node.data+1, maxi)) 

Click here for GitHub code

Leave A Comment

Your email address will not be published. Required fields are marked *