How To Validate a Binary Search tree in Python

admin

Administrator
Staff member
Here is a way to Validate a Binary Search tree in Python

Code:
def isValidBST(self, root): 
  
    # Base condition 
    if root is None: 
        return True
  
    # Check if left subtree is valid 
    if not self.isValidBST(root.left): 
        return False
  
    # Check if current node's value is greater than 
    # its left sub tree's max value 
    if (root.left and 
        root.val <= root.left.val): 
        return False
  
    # Check if right subtree is valid 
    if not self.isValidBST(root.right): 
        return False
  
    # Check if current node's value is lesser than 
    # its right sub tree's min value 
    if (root.right and 
        root.val >= root.right.val): 
        return False
  
    return True