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
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Binary Search Tree | Set 1 (Search and Insertion)
- Meta Binary Search | One-Sided Binary Search
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Find k-th smallest element in BST (Order Statistics in 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
- A program to check if a binary tree is BST or not
- Find the largest BST subtree in a given Binary Tree | Set 1
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Largest BST in a Binary Tree | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.