Check given array of size n can represent BST of n levels or not | A binary tree node has data , left child and right child ; To create a Tree with n levels . We always insert new node to left if it is less than previous value . ; Please refer below post for details of this function . www . geeksforgeeks . org / a - program - to - check - if - a - binary - tree - is - bst - or - not / https : ; Allow only distinct values ; Returns tree if given array of size n can represent a BST of n levels . ; Driver code
class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def createNLevelTree ( arr , n ) : NEW_LINE INDENT root = newNode ( arr [ 0 ] ) NEW_LINE temp = root NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( temp . key > arr [ i ] ) : NEW_LINE INDENT temp . left = newNode ( arr [ i ] ) NEW_LINE temp = temp . left NEW_LINE DEDENT else : NEW_LINE INDENT temp . right = newNode ( arr [ i ] ) NEW_LINE temp = temp . right NEW_LINE DEDENT DEDENT return root NEW_LINE DEDENT def isBST ( root , min , max ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root . key < min or root . key > max ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( isBST ( root . left , min , ( root . key ) - 1 ) and isBST ( root . right , ( root . key ) + 1 , max ) ) NEW_LINE DEDENT def canRepresentNLevelBST ( arr , n ) : NEW_LINE INDENT root = createNLevelTree ( arr , n ) NEW_LINE return isBST ( root , 0 , 2 ** 32 ) NEW_LINE DEDENT arr = [ 512 , 330 , 78 , 11 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE if ( canRepresentNLevelBST ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT