The Wayback Machine - https://web.archive.org/web/20240707120628/https://www.geeksforgeeks.org/largest-number-bst-less-equal-n/
Open In App

Largest number in BST which is less than or equal to N

Last Updated : 15 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

BST

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)
Recommended Practice

We follow recursive approach for solving this problem. We start searching for element from root node. If we reach a leaf and its value is greater than N, element does not exist so return -1. Else if node’s value is less than or equal to N and right value is NULL or greater than N, then return the node value as it will be the answer. 

Otherwise if node’s value is greater than N, then search for the element in the left subtree else search for the element in the right subtree by calling the same function by passing the left or right values accordingly. 

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 Node
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
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;
}
 
// function to find max value less than N
int findMaxforN(Node* root, int N)
{
    // Base cases
    if (root == NULL)
        return -1;
    if (root->key == N)
        return N;
 
    // If root's value is smaller, try in right
    // subtree
    else if (root->key < N) {
        int k = findMaxforN(root->right, N);
        if (k == -1)
            return root->key;
        else
            return k;
    }
 
    // If root's key is greater, return value
    // from left subtree.
    else if (root->key > N)
        return findMaxforN(root->left, N);   
}
 
// Driver code
int main()
{
    int N = 4;
 
    // creating following BST
    /*
                  5
               /   \
             2     12
           /  \    /  \
          1   3   9   21
                     /   \ 
                    19   25  */
    Node* 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);
 
    printf("%d", findMaxforN(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 = null;
    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;
}
 
// function to find max value less than N
static int findMaxforN(Node root, int N)
{
    // Base cases
    if (root == null)
        return -1;
    if (root.key == N)
        return N;
 
    // If root's value is smaller, try in right
    // subtree
    else if (root.key < N) {
        int k = findMaxforN(root.right, N);
        if (k == -1)
            return root.key;
        else
            return k;
    }
 
    // If root's key is greater, return value
    // from left subtree.
    else if (root.key > N)
        return findMaxforN(root.left, N);
    return -1;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4;
 
    // creating following BST
    /*
                5
            / \
            2     12
        / \ / \
        1 3 9 21
                    / \
                    19 25 */
    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));
}
}


Python3




# Python3 code to find the largest
# value smaller than or equal to N
class newNode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.key = data
        self.left = None
        self.right = None
 
# To insert a new node in BST
def 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
 
# function to find max value less than N
def findMaxforN(root, N):
     
    # Base cases
    if root == None:
        return -1
    if root.key == N:
        return N
 
    # If root's value is smaller, try in
    # right subtree
    elif root.key < N:
        k = findMaxforN(root.right, N)
        if k == -1:
            return root.key
        else:
            return k
 
    # If root's key is greater, return
    # value from left subtree.
    elif root.key > N:
        return findMaxforN(root.left, N)
 
# Driver code
if __name__ == '__main__':
    N = 4
 
    # creating following BST
    #
    #             5
    #         / \
    #         2     12
    #     / \ / \
    #     1 3 9 21
    #                 / \
    #             19 25
    root = None
    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)
    print(findMaxforN(root, N))
 
# This code is contributed by PranchalK


C#




// C# code to find the largest value
// smaller than or equal to N
using System;
 
class GFG
{
 
    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 = null;
        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;
    }
 
    // function to find max value less than N
    static int findMaxforN(Node root, int N)
    {
        // Base cases
        if (root == null)
            return -1;
        if (root.key == N)
            return N;
 
        // If root's value is smaller,
        // try in right subtree
        else if (root.key < N)
        {
            int k = findMaxforN(root.right, N);
            if (k == -1)
                return root.key;
            else
                return k;
        }
 
        // If root's key is greater, return
        // value from left subtree.
        else if (root.key > N)
            return findMaxforN(root.left, N);
        return -1;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int N = 4;
 
        // creating following BST
        /*
                    5
                / \
                2 12
            / \ / \
            1 3 9 21
                        / \
                        19 25 */
        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);
 
        Console.WriteLine(findMaxforN(root, N));
    }
}
 
// This code is contributed 29AjayKumar


Javascript




<script>
// javascript code to find the largest value smaller
// than or equal to N
     class Node
     {
         constructor(){
        this.key = 0;
        this.left = null,this.right = null;
    }
    }
 
    // To create new BST Node
    function newNode(item)
    {
        var temp = new Node();
        temp.key = item;
        temp.left = null;
        temp.right = null;
        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;
    }
 
    // function to find max value less than N
    function findMaxforN(root , N)
    {
     
        // Base cases
        if (root == null)
            return -1;
        if (root.key == N)
            return N;
 
        // If root's value is smaller, try in right
        // subtree
        else if (root.key < N)
        {
            var k = findMaxforN(root.right, N);
            if (k == -1)
                return root.key;
            else
                return k;
        }
 
        // If root's key is greater, return value
        // from left subtree.
        else if (root.key > N)
            return findMaxforN(root.left, N);
        return -1;
    }
 
    // Driver code
     
        var N = 4;
 
        // creating following BST
        /*
         * 5
         / \
         2 12
        / \ / \
        1 3 9 21
             / \
            19 25
         */
var 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);
 
        document.write(findMaxforN(root, N));
 
// This code is contributed by Rajput-Ji
</script>


Output

3

Time Complexity: O(h), where h is height of BST.
Auxiliary Space: O(h), The extra space is used in recursion call stack.

Iterative Solution: Below is an iterative solution and it does not require extra space for recursion call stack.  

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 Node
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
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;
}
 
// function to find max value less than N
void findMaxforN(Node* root, int N)
{
    // Start from root and keep looking for larger 
    while (root != NULL && root->right != NULL) {
 
        // If root is smaller go to right side
        if (N > root->key && N >= root->right->key)
            root = root->right;
 
        // If root is greater go to left side
        else if (N < root->key)
            root = root->left;
 
        else
            break;
    }
    if (root == NULL || root->key > N)
        cout << -1;
    else
        cout << root->key;
}
 
// Driver code
int main()
{
    int N = 50;
    Node* root = insert(root, 5);
    insert(root, 2);
    insert(root, 1);
    insert(root, 3);
    insert(root, 12);
    insert(root, 9);
    insert(root, 21);
    insert(root, 19);
    insert(root, 25);
 
    findMaxforN(root, N);
    return 0;
}


Java




// Java code to find the largest value smaller
// than or equal to N
import java.util.*;
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;
  }
 
  // function to find max value less than N
  static void findMaxforN(Node root, int N)
  {
    // Start from root and keep looking for larger 
    while (root != null && root.right != null) {
 
      // If root is smaller go to right side
      if (N > root.key && N >= root.right.key)
        root = root.right;
 
      // If root is greater go to left side
      else if (N < root.key)
        root = root.left;
 
      else
        break;
    }
    if (root == null || root.key > N)
      System.out.print(-1);
    else
      System.out.print(root.key);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 50;
    Node root = insert(null, 5);
    insert(root, 2);
    insert(root, 1);
    insert(root, 3);
    insert(root, 12);
    insert(root, 9);
    insert(root, 21);
    insert(root, 19);
    insert(root, 25);
 
    findMaxforN(root, N);
  }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 code to find the largest value
# smaller than or equal to N
 
class newNode:
     
    # To create new BST Node
    def __init__(self, data):
         
        self.key = data
        self.left = None
        self.right = None
 
# To insert a new node in BST
def 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
 
# Function to find max value less than N
def findMaxforN(root, N):
     
    # Start from root and keep looking for larger 
    while (root != None and root.right != None):
         
        # If root is smaller go to right side
        if (N > root.key and N >= root.right.key):
            root = root.right
 
        # If root is greater go to left side
        elif (N < root.key):
            root = root.left
        else:
            break
         
    if (root == None or root.key > N):
        print(-1)
    else:
        print(root.key)
 
# Driver code
if __name__ == '__main__':
     
    N = 50
     
    root = None
    root = insert(root, 5)
    insert(root, 2)
    insert(root, 1)
    insert(root, 3)
    insert(root, 12)
    insert(root, 9)
    insert(root, 21)
    insert(root, 19)
    insert(root, 25)
 
    findMaxforN(root, N)
 
# This code is contributed by bgangwar59


C#




// C# code to find the largest value smaller
// than or equal to N
using System;
 
public 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;
  }
 
  // function to find max value less than N
  static void findMaxforN(Node root, int N) {
    // Start from root and keep looking for larger
    while (root != null && root.right != null) {
 
      // If root is smaller go to right side
      if (N > root.key && N >= root.right.key)
        root = root.right;
 
      // If root is greater go to left side
      else if (N < root.key)
        root = root.left;
 
      else
        break;
    }
    if (root == null || root.key > N)
      Console.Write(-1);
    else
      Console.Write(root.key);
  }
 
  // Driver code
  public static void Main(String[] args) {
    int N = 50;
    Node root = insert(null, 5);
    insert(root, 2);
    insert(root, 1);
    insert(root, 3);
    insert(root, 12);
    insert(root, 9);
    insert(root, 21);
    insert(root, 19);
    insert(root, 25);
 
    findMaxforN(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(data)
    {
        this.key=data;
        this.left=this.right=null;
    }
}
 
function insert(node, key)
{
    // If tree is empty return new node
    if (node == null)
        return new Node(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
}
 
function findMaxforN(root, N)
{
    // Start from root and keep looking for larger
    while (root != null && root.right != null)
    {    
        // If root is smaller go to right side
        if (N > root.key && N >= root.right.key)
            root = root.right
  
        // If root is greater go to left side
        else if (N < root.key)
            root = root.left
        else
            break
    }    
    if (root == null || root.key > N)
        document.write(-1)
    else
        document.write(root.key)
}
let N = 50;
let root = null;
root=insert(root, 2)
root=insert(root, 1)
root=insert(root, 3)
root=insert(root, 12)
root=insert(root, 9)
root=insert(root, 21)
root=insert(root, 19)
root=insert(root, 25)
findMaxforN(root, N)
     
 
 
// This code is contributed by rag2127
 
</script>


Output

25

Time Complexity: O(h), where h is height of BST.
Auxiliary Space: O(1), As constant extra space is used.

   



Previous Article
Next Article

Similar Reads

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-&gt;12-&gt;21) Input : N
7 min read
Largest number with maximum trailing nines which is less than N and greater than N-D
Given two numbers N and D. The task is to find out the largest number smaller than or equal to N which contains the maximum number of trailing nines and the difference between N and the number should not be greater than D. Examples: Input: N = 1029, D = 102 Output: 999 1029 has 1 trailing nine while 999 has three trailing nine. Also 1029-999 = 30(w
14 min read
Find Largest Special Prime which is less than or equal to a given number
Given a number N. The task is to find the largest special prime which is less than or equal to N. A special prime is a number which can be created by placing digits one after another such the all the resulting numbers are prime.Examples: Input : N = 379 Output : 379 Explanation: 379 can be created as =&gt; 3 =&gt; 37 =&gt; 379 Here, all the numbers
9 min read
Smallest number in BST which is greater than or equal to N
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: Input: N = 20 Output: 21 Explanation: 21 is the smallest element greater than 20. Input: N = 18 Output: 19 Explanation: 19 is the s
9 min read
Smallest number in BST which is greater than or equal to N ( Iterative Approach)
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Examples: Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST
8 min read
Largest number less than N with digit sum greater than the digit sum of N
Given an integer N, the task is to find the greatest number less than N such that the sum of its digits is greater than the sum of the digits of N. If the condition isn't satisfied for any number then print -1.Examples: Input: N = 100 Output: 99 99 is the largest number less than 100 sum of whose digits is greater than the sum of the digits of 100I
9 min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k'th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height
15+ min read
Sum of largest prime factor of each number less than equal to n
Given a non-negative integer n. The problem is to find the sum of the largest prime factor of each number less than equal to n. Examples: Input : n = 10 Output : 32 Largest prime factor of each number Prime factor of 2 = 2 Prime factor of 3 = 3 Prime factor of 4 = 2 Prime factor of 5 = 5 Prime factor of 6 = 3 Prime factor of 7 = 7 Prime factor of 8
8 min read
Largest number less than or equal to Z that leaves a remainder X when divided by Y
Given three integers x, y, z, the task is to find the largest non-negative number less than or equal to z that leaves a remainder x when divided by y (Given x &lt; y). If no such number exists then the output will be -1. Examples: Input: x = 1, y = 5, z = 8 Output: 6 Explanation: 6 is the largest number less than 8 which when divided by 5 leaves a
5 min read
Largest number less than equal to N having exactly K set bits
Given two positive integers N and K, we need to determine if there exists a positive integer X less than or equal to N such that the number of 1s in the binary representation of X is equal to k (i.e., f(X) = K). If such an X exists, we also need to find the maximum value of X and print -1 if there is no such positive integer X. Constraints: 1 &lt;=
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg