text: Largest number in BST which is less than or equal to N | Java code to find the largest value smaller than or equal to N ; Node structure ; 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 ; 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
code: class GfG { static class Node { int key ; Node left , right ; } static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . left = null ; temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } static int findMaxforN ( Node root , int N ) { if ( root == null ) return - 1 ; if ( root . key == N ) return N ; else if ( root . key < N ) { int k = findMaxforN ( root . right , N ) ; if ( k == - 1 ) return root . key ; else return k ; } else if ( root . key > N ) return findMaxforN ( root . left , N ) ; return - 1 ; } public static void main ( String [ ] args ) { int N = 4 ; Node root = null ; root = insert ( root , 25 ) ; insert ( root , 2 ) ; insert ( root , 1 ) ; insert ( root , 3 ) ; insert ( root , 12 ) ; insert ( root , 9 ) ; insert ( root , 21 ) ; insert ( root , 19 ) ; insert ( root , 25 ) ; System . out . println ( findMaxforN ( root , N ) ) ; } }