Largest number less than or equal to N in BST ( Iterative Approach ) | 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 ; Returns largest value smaller than or equal to key . If key is smaller than the smallest , it returns - 1. ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . key = item 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 findFloor ( root , key ) : NEW_LINE INDENT curr = root NEW_LINE ans = None NEW_LINE while ( curr ) : NEW_LINE INDENT if ( curr . key <= key ) : NEW_LINE INDENT ans = curr NEW_LINE curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT curr = curr . left NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT return ans . key NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE root = None NEW_LINE root = insert ( root , 19 ) 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 print ( findFloor ( root , N ) ) NEW_LINE DEDENT