A program to check if a binary tree is BST or not |  ; Helper function that allocates a new node with the given data and None left and right poers . ; Returns true if given tree is BST . ; Base condition ; if left node exist then check it has correct data or not i . e . left node ' s ▁ data ▁ ▁ should ▁ be ▁ less ▁ than ▁ root ' s data ; if right node exist then check it has correct data or not i . e . right node ' s ▁ data ▁ ▁ should ▁ be ▁ greater ▁ than ▁ root ' s data ; check recursively for every node . ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isBST ( root , l = None , r = None ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( l != None and root . data <= l . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( r != None and root . data >= r . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT return isBST ( root . left , l , root ) and isBST ( root . right , root , r ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 3 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 1 ) NEW_LINE root . right . right = newNode ( 4 ) NEW_LINE if ( isBST ( root , None , None ) ) : NEW_LINE INDENT print ( " Is ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ a ▁ BST " ) NEW_LINE DEDENT DEDENT