Largest number in BST which is less than or equal to N | Constructor to create a new 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 ; Base cases ; If root 's value is smaller, try in  right subtree ; If root 's key is greater, return  value from left subtree. ; Driver code ; creating following BST 5 / \ 2 12 / \ / \ 1 3 9 21 / \ 19 25
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 if root == None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if root . key == N : NEW_LINE INDENT return N NEW_LINE DEDENT elif root . key < N : NEW_LINE INDENT k = findMaxforN ( root . right , N ) NEW_LINE if k == - 1 : NEW_LINE INDENT return root . key NEW_LINE DEDENT else : NEW_LINE INDENT return k NEW_LINE DEDENT DEDENT elif root . key > N : NEW_LINE INDENT return findMaxforN ( root . left , N ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE root = None NEW_LINE root = insert ( root , 25 ) 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 ( findMaxforN ( root , N ) ) NEW_LINE DEDENT