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.
- Inorder predecessor and successor for a given key in BST | Iterative Approach
- Largest number in BST which is less than or equal to N
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Smallest number in BST which is greater than or equal to N
- Root to leaf path sum equal to a given number in BST
- Longest sub-array with equal number of alphabets and numeric characters
- Coin Change | BFS Approach
- Check if a Binary Tree is BST : Simple and Efficient Approach
- Josephus Problem | (Iterative Solution)
- QuickSelect (A Simple Iterative Implementation)
- C Program for Binary Search (Recursive and Iterative)
- Iterative searching in Binary Search Tree
- Largest gap in an array
- Second largest element in BST
- Sum of k largest elements in BST
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.