Largest number less than or equal to N in BST ( Iterative Approach ) | Javascript 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 Node { constructor ( item ) { this . key = item ; this . left = null ; this . right = null ; } } function newNode ( item ) { let temp = new Node ( item ) ; return temp ; } function insert ( node , 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 ; } function findFloor ( root , key ) { let curr = root , ans = null ; while ( curr != null ) { if ( curr . key <= key ) { ans = curr ; curr = curr . right ; } else curr = curr . left ; } if ( ans != null ) return ans . key ; return - 1 ; } let N = 25 ; let root = new Node ( N ) ; insert ( root , 19 ) ; insert ( root , 2 ) ; insert ( root , 1 ) ; insert ( root , 3 ) ; insert ( root , 12 ) ; insert ( root , 9 ) ; insert ( root , 21 ) ; insert ( root , 19 ) ; insert ( root , 25 ) ; document . write ( findFloor ( root , N ) ) ;