Largest number less than or equal to N in BST ( Iterative Approach ) | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } 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 ; } int findFloor ( Node * root , int key ) { Node * curr = root , * ans = NULL ; while ( curr ) { if ( curr -> key <= key ) { ans = curr ; curr = curr -> right ; } else curr = curr -> left ; } if ( ans ) return ans -> key ; return -1 ; } int main ( ) { int N = 25 ; Node * root = 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 ) ; printf ( " % d " , findFloor ( root , N ) ) ; return 0 ; }