A program to check if a binary tree is BST or not | Python3 program to check if a given tree is BST . ; A binary tree node has data , pointer to left child and a pointer to right child ; traverse the tree in inorder fashion and keep track of prev node ; Allows only distinct valued nodes ; Driver Code
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isBSTUtil ( root , prev ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT if ( isBSTUtil ( root . left , prev ) == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prev != None and root . data <= prev . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev = root NEW_LINE return isBSTUtil ( root . right , prev ) NEW_LINE DEDENT return True NEW_LINE DEDENT def isBST ( root ) : NEW_LINE INDENT prev = None NEW_LINE return isBSTUtil ( root , prev ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 3 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 1 ) NEW_LINE root . right . right = Node ( 4 ) NEW_LINE if ( isBST ( root ) == None ) : NEW_LINE INDENT print ( " Is ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ a ▁ BST " ) NEW_LINE DEDENT DEDENT