VOOZH about

URL: https://www.geeksforgeeks.org/dsa/floor-and-ceil-from-a-bst/

⇱ Ceil in a BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Ceil in a BST

Last Updated : 31 Jan, 2026

Given a Binary Search Tree and a value x, find the ceil value of x .Ceil means the smallest node value greater than or equal to the x.

Example:

Input:  x=11

👁 bst4

Output: 12
Explanation: 12 is the smallest value greater than or equal to 11.

Input: x=4

👁 bst3

Output: 4

[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:


Output
12


Comment
Article Tags: