Largest number less than or equal to N in BST (Iterative Approach) - GeeksforGeeks

09 Aug, 2021
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1.  
Examples: For the above given binary search tree- 
Input : N = 24
Output :result = 21
(searching for 24 will be like-5->12->21)

Input  : N = 4
Output : result = 3
(searching for 4 will be like-5->2->3)
We have discussed recursive approach in below post. Largest number in BST which is less than or equal to NHere an iterative approach is discussed. We try to find the predecessor of the target. Keep two pointers, one pointing to the current node and one for storing the answer. If the current node’s data > N, we move towards left. In other case, when current node’s data is less than N, the current node can be our answer (so far), and we move towards right. 
C++
Java
Python3
C#
Javascript
// C++ code to find the largest value smaller// than or equal to N#include <bits/stdc++.h>using namespace std; struct Node {    int key;    Node *left, *right;}; // To create new BST NodeNode* newNode(int item){    Node* temp = new Node;    temp->key = item;    temp->left = temp->right = NULL;    return temp;} // To insert a new node in BSTNode* insert(Node* node, int key){    // if tree is empty return new node    if (node == NULL)        return newNode(key);     // if key is less then or greater then    // node value then recur down the tree    if (key < node->key)        node->left = insert(node->left, key);    else if (key > node->key)        node->right = insert(node->right, key);     // return the (unchanged) node pointer    return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.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;} // Driver codeint 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;}
// Java code to find the largest value smaller// than or equal to Nclass GFG{     static class Node{    int key;    Node left, right;}; // To create new BST Nodestatic Node newNode(int item){    Node temp = new Node();    temp.key = item;    temp.left = temp.right = null;    return temp;} // To insert a new node in BSTstatic Node insert(Node node, int key){    // if tree is empty return new node    if (node == null)        return newNode(key);     // if key is less then or greater then    // node value then recur down the tree    if (key < node.key)        node.left = insert(node.left, key);    else if (key > node.key)        node.right = insert(node.right, key);     // return the (unchanged) node pointer    return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.static int findFloor(Node root, int key){    Node 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;} // Driver codepublic static void main(String[] args){    int N = 25;     Node root = new Node();    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);     System.out.printf("%d", findFloor(root, N));}} /* This code is contributed by PrinciRaj1992 */
# Python3 code to find the largest value# smaller than or equal to N class newNode:         def __init__(self, item):                 self.key = item        self.left = None        self.right = None # To insert a new node in BSTdef insert(node, key):         # If tree is empty return new node    if (node == None):        return newNode(key)     # If key is less then or greater then    # node value then recur down the tree    if (key < node.key):        node.left = insert(node.left, key)    elif (key > node.key):        node.right = insert(node.right, key)     # Return the (unchanged) node pointer    return node # Returns largest value smaller than or# equal to key. If key is smaller than# the smallest, it returns -1.def findFloor(root, key):         curr = root    ans = None         while (curr):        if (curr.key <= key):            ans = curr            curr = curr.right        else:            curr = curr.left    if (ans):        return ans.key             return -1 # Driver codeif __name__ == '__main__':         N = 25    root = None     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)     print(findFloor(root, N)) # This code is contributed by bgangwar59
// C# code to find the largest value smaller// than or equal to Nusing System;using System.Collections.Generic;     class GFG{     public class Node{    public int key;    public Node left, right;}; // To create new BST Nodestatic Node newNode(int item){    Node temp = new Node();    temp.key = item;    temp.left = temp.right = null;    return temp;} // To insert a new node in BSTstatic Node insert(Node node, int key){    // if tree is empty return new node    if (node == null)        return newNode(key);     // if key is less then or greater then    // node value then recur down the tree    if (key < node.key)        node.left = insert(node.left, key);    else if (key > node.key)        node.right = insert(node.right, key);     // return the (unchanged) node pointer    return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.static int findFloor(Node root, int key){    Node 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;} // Driver codepublic static void Main(String[] args){    int N = 25;     Node root = new Node();    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);     Console.Write("{0}", findFloor(root, N));}} // This code is contributed by Rajput-Ji
<script> // Javascript code to find the largest// value smaller than or equal to Nclass Node{    constructor(item)    {        this.key = item;        this.left = null;        this.right = null;    }} // To create new BST Nodefunction newNode(item){    let temp = new Node(item);    return temp;} // To insert a new node in BSTfunction insert(node, key){         // If tree is empty return new node    if (node == null)        return newNode(key);     // If key is less then or greater then    // node value then recur down the tree    if (key < node.key)        node.left = insert(node.left, key);    else if (key > node.key)        node.right = insert(node.right, key);     // Return the (unchanged) node pointer    return node;} // Returns largest value smaller than or// equal to key. If key is smaller than// the smallest, it returns -1.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;} // Driver codelet 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)); // This code is contributed by divyeshrabadiya07 </script>
Output: 
25
YouTubeGeeksforGeeks506K subscribersLargest number less than or equal to N in BST (Iterative Approach) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3EL8c9bBeco" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
princiraj1992
Rajput-Ji
bgangwar59
divyeshrabadiya07
akshaysingh98088
Binary Search Tree
Searching
Searching
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Construct BST from given preorder traversal | Set 2
Red Black Tree vs AVL Tree
Print BST keys in the given range
Find the node with maximum value in a Binary Search Tree
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number