Given a BST, find the floor and ceil of a given key in it. If the given key lies in the BST, then both floor and ceil are equal to that key; otherwise, the ceil is equal to the next greater key (if any) in the BST, and the floor is equal to the previous greater key (if any) in the BST.

For example, consider the following tree:

Floor and Ceil of BST

The floor of 1 does not exist, ceil of 1 is 2
The floor of 3 is 2, ceil of 3 is 4
The floor of 9 is 9, ceil of 9 is 9
The floor of 7 is 6, ceil of 7 is 8

Practice this problem

The idea is simple – search for the given key in the tree and update the ceil to the current node before visiting its left subtree. Similarly, update the floor to the current node before visiting its right subtree. If the key is found in the BST, then the floor and ceil are equal to that key. If the key is not found in the BST, then the floor and ceil were already updated while searching for the key.

Following is the iterative implementation of the above approach in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
0 —> Floor is -1, Ceil is 2
1 —> Floor is -1, Ceil is 2
2 —> Floor is 2, Ceil is 2
3 —> Floor is 2, Ceil is 4
4 —> Floor is 4, Ceil is 4
5 —> Floor is 4, Ceil is 6
6 —> Floor is 6, Ceil is 6
7 —> Floor is 6, Ceil is 8
8 —> Floor is 8, Ceil is 8
9 —> Floor is 9, Ceil is 9
10 —> Floor is 10, Ceil is 10
11 —> Floor is 10, Ceil is 12
12 —> Floor is 12, Ceil is 12
13 —> Floor is 12, Ceil is -1
14 —> Floor is 12, Ceil is -1

The time complexity of the above solution is O(n), where n is the size of the BST. The auxiliary space required by the program is O(1).

 
Following is the recursive C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.