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

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 N
Here 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.Â
Implementation:
C++
// 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 than or greater than    // 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
// Java code to find the largest value smaller // than or equal to N class GFG{Â Â Â Â Â static class Node{ Â Â Â Â int key; Â Â Â Â Node left, right; }; Â
// To create new BST Node static Node newNode(int item) { Â Â Â Â Node temp = new Node(); Â Â Â Â temp.key = item; Â Â Â Â temp.left = temp.right = null; Â Â Â Â return temp; } Â
// To insert a new node in BST static Node insert(Node node, int key) {     // if tree is empty return new node     if (node == null)         return newNode(key); Â
    // if key is less than or greater than     // 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 code public 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
# 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 than or greater than    # 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#
// C# code to find the largest value smaller // than or equal to N using System;using System.Collections.Generic; Â Â Â Â Â class GFG{Â Â Â Â Â public class Node{ Â Â Â Â public int key; Â Â Â Â public Node left, right; }; Â
// To create new BST Node static Node newNode(int item) { Â Â Â Â Node temp = new Node(); Â Â Â Â temp.key = item; Â Â Â Â temp.left = temp.right = null; Â Â Â Â return temp; } Â
// To insert a new node in BST static Node insert(Node node, int key) {     // if tree is empty return new node     if (node == null)         return newNode(key); Â
    // if key is less than or greater than     // 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 code public 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 |
Javascript
<script>Â
// Javascript code to find the largest // value smaller than or equal to N class Node{Â Â Â Â constructor(item)Â Â Â Â {Â Â Â Â Â Â Â Â this.key = item;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}Â
// To create new BST Node function newNode(item) { Â Â Â Â let temp = new Node(item); Â Â Â Â return temp; } Â
// To insert a new node in BST function insert(node, key) {          // If tree is empty return new node     if (node == null)         return newNode(key); Â
    // If key is less than or greater than     // 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> |
25
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




