Largest number in BST which is less than or equal to N | Python3 code to find the largest value smaller than or equal to N ; To create new BST Node ; To insert a new node in BST ; If tree is empty return new node ; If key is less then or greater then node value then recur down the tree ; Return the ( unchanged ) node pointer ; Function to find max value less then N ; Start from root and keep looking for larger ; If root is smaller go to right side ; If root is greater go to left side ; 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 insert ( node , key ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if ( key < node . key ) : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif ( key > node . key ) : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def findMaxforN ( root , N ) : NEW_LINE INDENT while ( root != None and root . right != None ) : NEW_LINE INDENT if ( N > root . key and N >= root . right . key ) : NEW_LINE INDENT root = root . right NEW_LINE DEDENT elif ( N < root . key ) : NEW_LINE INDENT root = root . left NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( root == None or root . key > N ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( root . key ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 50 NEW_LINE root = None NEW_LINE root = insert ( root , 5 ) NEW_LINE insert ( root , 2 ) NEW_LINE insert ( root , 1 ) NEW_LINE insert ( root , 3 ) NEW_LINE insert ( root , 12 ) NEW_LINE insert ( root , 9 ) NEW_LINE insert ( root , 21 ) NEW_LINE insert ( root , 19 ) NEW_LINE insert ( root , 25 ) NEW_LINE findMaxforN ( root , N ) NEW_LINE DEDENT