[Approach 1] Using Recursion - O(h) Time and O(h) Space
The idea is to find the ceil value recursively: if the current node’s value is greater than or equal to x, consider it as a answer and move left for a closer value; otherwise, move right to search for a larger value.
Steps to solve the problem:
Set ans = -1
While node exists:
If node->data == key, return key.
If key < node->data, set ans = node->data and move left (maybe there’s a smaller valid value).
Else (key > node->data), move right (need a bigger value).
Return ans.
Output
12
Time complexity: O(h) where h is height of the given BST Auxiliary Space: O(h)
[Approach 2] Using Iterative Way - O(h) Time and O(1) Space
The idea is to traverse the BST: if the current node’s value is ≥ x, move left to try for a smaller valid value; otherwise, move right to look for a greater value.
Below is the implementation of the above approach: