Given a Binary Search Tree and a number x, we have to find the floor of x in the given BST, where floor means the greatest value node of the BST which is smaller than or equal to x. if x is smaller than the smallest node of BST then return -1.
[Expected Approach - 1] Using Recursion - O(h) Time and O(h) Space
The idea is to find the floor in a BST by traversing recursively: if the nodeβs value is greater than the key, move left; if it is less than or equal to the key, record it and move right.
Follow the given steps to solve the problem:
Start at the root node.
If root->data == x, the floor of x is equal to the root.
Else if root->data > x, the floor must lie in the left subtree.
Otherwise, search in the right subtree for a value less than or equal to x, but if not found, the root itself is the floor.
Output
12
[Expected Approach - 2] Iterative Solution- O(h) Time and O(1) Space
The idea is to iteratively traverse the BST to find the greatest value smaller than or equal to x. If the current node's data is greater than x, move left. If it's smaller, update the floor value and move right. This process continues until the closest floor value is found.
Below is the implementation of the above approach: