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 ciel of BST you can refer to this article.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Floor value Kth root of a number using Recursive Binary Search
- Binary Search Tree | Set 1 (Search and Insertion)
- 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
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Binary Tree to Binary Search Tree Conversion
- Binary Search Tree | Set 2 (Delete)
- Optimal Binary Search Tree | DP-24
- Sum of all the levels in a Binary Search Tree
- Make Binary Search Tree
- How to handle duplicates in Binary Search Tree?
- Print all odd nodes of Binary Search Tree
- Threaded Binary Search Tree | Deletion
- Print Binary Search Tree in Min Max Fashion
- Iterative searching in Binary Search Tree
- Construct a Binary Search Tree from given postorder
- Number of pairs with a given sum in a Binary Search Tree
- Binary Search Tree | Set 3 (Iterative Delete)
- Print all even nodes of Binary Search Tree
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.