Given a Binary Search Tree and a number x, find floor of x in the given BST.
Input : x = 14 and root of below tree 10 / \ 5 15 / \ 12 30 Output : 12 Input : x = 15 and root of below tree 10 / \ 5 15 / \ 12 30 Output : 15
A simple solution is to traverse the tree using (Inorder or Preorder or Postorder) and keep track of closest smaller or same element. Time complexity of this solution is O(n) where n is total number of Nodes in BST.
We can efficiently find closest smaller or same element in O(h) time where h is height of BST. Algorithm to find the floor of a key in a binary search tree (BST):
1 Start at the root Node. 2 If root->data == key, floor of the key is equal to the root. 3 Else if root->data > key, then floor of the key must lie in the left subtree. 4 Else floor may lie in the right subtree but only if there is a value lesser than or equal to the key.If not, then root is the key.
For finding ceil of BST you can refer to this article.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Floor value Kth root of a number using Recursive Binary Search
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Floor and Ceil from a BST
- Count permutations of given array that generates the same Binary Search Tree (BST)
- Binary Tree to Binary Search Tree Conversion
- Difference between Binary Tree and Binary Search Tree
- Binary Tree to Binary Search Tree Conversion using STL set
- Binary Search Tree | Set 1 (Search and Insertion)
- Meta Binary Search | One-Sided Binary Search
- Two nodes of a BST are swapped, correct the BST | Set-2
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Count the Number of Binary Search Trees present in a Binary Tree
- Interpolation search vs Binary search
- Why is Binary Search preferred over Ternary Search?
- Linear Search vs Binary Search
- A program to check if a binary tree is BST or not
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.