Open In App

Ceil in a BST

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary search tree and a key(node) value, find the ceil value for that particular key value. Please note that we have already discussed floor in BST

Example:

           8
        /   \    
     4      12
   /  \    /  \
2    6  10   14

Key: 11  Ceil: 12
Key: 1   Ceil: 2
Key: 6  Ceil: 6
Key: 15 Ceil: -1

There are numerous applications where we need to find the floor/ceil value of a key in a binary search tree or sorted array. For example, consider designing a memory management system in which free nodes are arranged in BST. Find the best fit for the input request.

Ceil in Binary Search Tree using Recursion:

To solve the problem follow the below idea:

Imagine we are moving down the tree, and assume we are root node. 
The comparison yields three possibilities,

A) Root data is equal to key. We are done, root data is ceil value.

B) Root data < key value, certainly the ceil value can't be in left subtree. 
     Proceed to search on right subtree as reduced problem instance.

C) Root data > key value, the ceil value may be in left subtree. 
     We may find a node with is larger data than key value in left subtree, 
     if not the root itself will be ceil node.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int key;
    Node* left;
    Node* right;
    Node(int value) {
        key = value;
        left = right = nullptr;
    }
};

// Function to find the ceiling of a given 
// input in BST. If the input is more than
// the max key in BST, return -1.
int findCeil(Node* root, int input) {
  
    // Base case
    if (root == nullptr)
        return -1;

    // We found equal key
    if (root->key == input)
        return root->key;

    // If root's key is smaller, 
    // ceil must be in the right subtree
    if (root->key < input)
        return findCeil(root->right, input);

    // Else, either left subtree or
    // root has the ceil value
    int ceil = findCeil(root->left, input);
    return (ceil >= input) ? ceil : root->key;
}

// Driver code
int main() {
    Node* root = new Node(8);
    root->left = new Node(4);
    root->right = new Node(12);
    root->left->left = new Node(2);
    root->left->right = new Node(6);
    root->right->left = new Node(10);
    root->right->right = new Node(14);

    // Testing for values from 0 to 15
    for (int i = 0; i < 16; i++)
        cout << i << " " << findCeil(root, i) << endl;

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Structure of each Node in the tree
struct Node {
    int key;
    struct Node* left;
    struct Node* right;
};

// Function to find the ceiling of a given 
// input in BST. If the input is more than
// the max key in BST, return -1.
int findCeil(struct Node* root, int input) {
    // Base case
    if (root == NULL)
        return -1;

    // We found equal key
    if (root->key == input)
        return root->key;

    // If root's key is smaller, 
    // ceil must be in the right subtree
    if (root->key < input)
        return findCeil(root->right, input);

    // Else, either left subtree or
    // root has the ceil value
    int ceil = findCeil(root->left, input);
    return (ceil >= input) ? ceil : root->key;
}

// Function to create a new node
struct Node* newNode(int key) {
    struct Node* node = 
      (struct Node*)malloc(sizeof(struct Node));
    node->key = key;
    node->left = node->right = NULL;
    return node;
}

// Driver code
int main() {
    struct Node* root = newNode(8);
    root->left = newNode(4);
    root->right = newNode(12);
    root->left->left = newNode(2);
    root->left->right = newNode(6);
    root->right->left = newNode(10);
    root->right->right = newNode(14);

    // Testing for values from 0 to 15
    for (int i = 0; i < 16; i++)
        printf("%d %d\n", i, findCeil(root, i));

    return 0;
}
Java
class Node {
    int key;
    Node left, right;

    Node(int value) {
        key = value;
        left = right = null;
    }
}

// Function to find the ceiling of a given input in BST.
// If the input is more than the max key in BST, return -1.
public class GfG {
    
    static int findCeil(Node root, int input) {
      
        // Base case
        if (root == null) {
            return -1;
        }

        // We found equal key
        if (root.key == input) {
            return root.key;
        }

        // If root's key is smaller, 
        // ceil must be in the right subtree
        if (root.key < input) {
            return findCeil(root.right, input);
        }

        // Else, either left subtree or root
        // has the ceil value
        int ceil = findCeil(root.left, input);
        return (ceil >= input) ? ceil : root.key;
    }

    public static void main(String[] args) {
        Node root = new Node(8);
        root.left = new Node(4);
        root.right = new Node(12);
        root.left.left = new Node(2);
        root.left.right = new Node(6);
        root.right.left = new Node(10);
        root.right.right = new Node(14);

        // Testing for values from 0 to 15
        for (int i = 0; i < 16; i++) {
            System.out.println(i + " " + findCeil(root, i));
        }
    }
}
Python
class Node:
    def __init__(self, value):
        self.key = value
        self.left = None
        self.right = None

# Function to find the ceiling of a given input in BST.
# If the input is more than the max key in BST, return -1.
def find_ceiling(root, input):
    # Base case
    if root is None:
        return -1

    # We found equal key
    if root.key == input:
        return root.key

    # If root's key is smaller, 
    # ceil must be in the right subtree
    if root.key < input:
        return find_ceiling(root.right, input)

    # Else, either left subtree or root has the ceil value
    ceil = find_ceiling(root.left, input)
    return ceil if ceil >= input else root.key

# Driver code
if __name__ == "__main__":
    root = Node(8)
    root.left = Node(4)
    root.right = Node(12)
    root.left.left = Node(2)
    root.left.right = Node(6)
    root.right.left = Node(10)
    root.right.right = Node(14)

    # Testing for values from 0 to 15
    for i in range(16):
        print(find_ceiling(root, i))
C#
using System;

class Node {
    public int Key;
    public Node Left, Right;

    public Node(int value) {
        Key = value;
        Left = Right = null;
    }
}

class GfG {
  
    // Function to find the ceiling of a given input in BST.
    // If the input is more than the max key in BST, return -1.
    static int FindCeil(Node root, int input) {
      
        // Base case
        if (root == null) {
            return -1;
        }

        // We found equal key
        if (root.Key == input) {
            return root.Key;
        }

        // If root's key is smaller, 
        // ceil must be in the right subtree
        if (root.Key < input) {
            return FindCeil(root.Right, input);
        }

        // Else, either left subtree or root 
        // has the ceil value
        int ceil = FindCeil(root.Left, input);
        return (ceil >= input) ? ceil : root.Key;
    }

    static void Main() {
        Node root = new Node(8);
        root.Left = new Node(4);
        root.Right = new Node(12);
        root.Left.Left = new Node(2);
        root.Left.Right = new Node(6);
        root.Right.Left = new Node(10);
        root.Right.Right = new Node(14);

        // Testing for values from 0 to 15
        for (int i = 0; i < 16; i++) {
            Console.WriteLine($"{i} {FindCeil(root, i)}");
        }
    }
}
JavaScript
class Node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}

// Function to find the ceiling of a given input in BST.
// If the input is more than the max key in BST, return -1.
function findCeil(root, input) {
    // Base case
    if (root === null) {
        return -1;
    }

    // We found equal key
    if (root.key === input) {
        return root.key;
    }

    // If root's key is smaller, 
    // ceil must be in the right subtree
    if (root.key < input) {
        return findCeil(root.right, input);
    }

    // Else, either left subtree or root has the ceil value
    const ceil = findCeil(root.left, input);
    return (ceil >= input) ? ceil : root.key;
}

// Driver code
const root = new Node(8);
root.left = new Node(4);
root.right = new Node(12);
root.left.left = new Node(2);
root.left.right = new Node(6);
root.right.left = new Node(10);
root.right.right = new Node(14);

// Testing for values from 0 to 15
for (let i = 0; i < 16; i++) {
    console.log(`${i} ${findCeil(root, i)}`);
}

Time complexity: O(h) where h is height of the given BST 
Auxiliary Space: O(h)

Iterative Approach to find Ceil:

The idea is same as the recursive approach. But this approach is more efficient as it does not require auxiliary space and no recursion call overhead. To solve the problem follow the below steps:

  • If the tree is empty, i.e. root is null, return back to the calling function.
  • If the current node address is not null, perform the following steps : 
    • If the current node data matches with the key value - We have found both our floor and ceil value. 
      Hence, we return back to the calling function.
    • If data in the current node is lesser than the key value - We assign the current node data to the variable keeping
      track of current floor value and explore the right subtree, as it may contain nodes with values greater than the key value.
    • If data in the current node is greater than the key value - We assign the current node data to the variable keeping track
      of current ceil value and explore the left subtree, as it may contain nodes with values lesser than the key value.
  • Once we reach null, we return back to the calling function, as we have got our required floor and ceil values for the particular key value.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left, *right;
    Node(int value) {
        data = value;
        left = right = nullptr;
    }
};

// Helper function to find ceil of a given key in BST
int findCeil(Node* root, int key) {
  
    int ceil = -2; 

    while (root) {
      
        // If root itself is ceil
        if (root->data == key) {
            return root->data; 
        }
 
        // If root is smaller, the ceil
        // must be in the right subtree
        if (key > root->data) {
            root = root->right; 
        } 
      
        // Else either root can be ceil
        // or a node in the left child
        else {
            ceil = root->data; 
            root = root->left; 
        }
    }
    return ceil; 
}

// Driver code
int main() {
    Node* root = new Node(8);
    root->left = new Node(4);
    root->right = new Node(12);
    root->left->left = new Node(2);
    root->left->right = new Node(6);
    root->right->left = new Node(10);
    root->right->right = new Node(14);

    for (int i = 0; i < 16; i++)
        cout << findCeil(root, i) << "\n";

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Structure for a tree node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Helper function to find ceil of a given
// key in BST
int findCeil(struct Node* root, int key) {
  
    int ceil = -1;  // -1 indicates no ceiling found yet

    while (root) {
      
        // If root itself is ceil
        if (root->data == key) {
            return root->data;
        }

        // If root is smaller, the ceil 
        // must be in the right subtree
        if (key > root->data) {
            root = root->right;
        } 
      
        // Else either root can be ceil 
        // or a node in the left child
        else {
            ceil = root->data;
            root = root->left;
        }
    }
    return ceil; 
}

// Function to create a new node
struct Node* newNode(int key) {
    struct Node* node = 
      (struct Node*)malloc(sizeof(struct Node));
    node->key = key;
    node->left = node->right = NULL;
    return node;
}

// Driver code
int main() {
    struct Node* root = newNode(8);
    root->left = newNode(4);
    root->right = newNode(12);
    root->left->left = newNode(2);
    root->left->right = newNode(6);
    root->right->left = newNode(10);
    root->right->right = newNode(14);

    for (int i = 0; i < 16; i++) {
        printf("%d\n", findCeil(root, i));
    }

    return 0;
}
Java
class Node {
    int data;
    Node left, right;

    Node(int value) {
        data = value;
        left = right = null;
    }
}

// Function to find the ceiling of a given
// input in BST. If the input is more than
// the max key in BST, return -1.
class GfG {
  
    static int findCeil(Node root, int key) {
        int ceil = -1;  // -1 indicates no ceiling found yet

        while (root != null) {
            // If root itself is ceil
            if (root.data == key) {
                return root.data;
            }

            // If root's data is smaller, 
            // ceil must be in the right subtree
            if (key > root.data) {
                root = root.right;
            } 
            // Else either root can be ceil 
            // or a node in the left child
            else {
                ceil = root.data;
                root = root.left;
            }
        }
        return ceil;
    }

    public static void main(String[] args) {
        Node root = new Node(8);
        root.left = new Node(4);
        root.right = new Node(12);
        root.left.left = new Node(2);
        root.left.right = new Node(6);
        root.right.left = new Node(10);
        root.right.right = new Node(14);

        // Testing for values from 0 to 15
        for (int i = 0; i < 16; i++) {
            System.out.println(findCeil(root, i));
        }
    }
}
Python
class Node:
    def __init__(self, value):
        self.data = value
        self.left = None
        self.right = None

# Helper function to find the ceiling
# of a given key in BST
def find_ceiling(root, key):
  
    ceil = -1  # -1 indicates no ceiling found yet

    while root:
      
        # If root itself is ceil
        if root.data == key:
            return root.data

        # If root's data is smaller, 
        # ceil must be in the right subtree
        if key > root.data:
            root = root.right
        else:
          
            # Else either root can be ceil 
            # or a node in the left child
            ceil = root.data
            root = root.left
    
    return ceil

# Driver code
root = Node(8)
root.left = Node(4)
root.right = Node(12)
root.left.left = Node(2)
root.left.right = Node(6)
root.right.left = Node(10)
root.right.right = Node(14)

# Testing for values from 0 to 15
for i in range(16):
    print(find_ceiling(root, i))
C#
using System;

class Node {
    public int Data;
    public Node Left, Right;

    public Node(int value) {
        Data = value;
        Left = Right = null;
    }
}

class GfG {
  
    // Function to find the ceiling of a given input in BST.
    // If the input is more than the max key in BST, return -1.
    static int FindCeil(Node root, int key) {
        int ceil = -1; // -1 indicates no ceiling found yet

        while (root != null) {
            // If root itself is ceil
            if (root.Data == key) {
                return root.Data;
            }

            // If root's data is smaller, 
            // ceil must be in the right subtree
            if (key > root.Data) {
                root = root.Right;
            } 
            // Else either root can be ceil 
            // or a node in the left child
            else {
                ceil = root.Data;
                root = root.Left;
            }
        }
        return ceil;
    }

    static void Main() {
        Node root = new Node(8);
        root.Left = new Node(4);
        root.Right = new Node(12);
        root.Left.Left = new Node(2);
        root.Left.Right = new Node(6);
        root.Right.Left = new Node(10);
        root.Right.Right = new Node(14);

        // Testing for values from 0 to 15
        for (int i = 0; i < 16; i++) {
            Console.WriteLine(FindCeil(root, i));
        }
    }
}
JavaScript
class Node {
    constructor(value) {
        this.data = value;
        this.left = null;
        this.right = null;
    }
}

// Helper function to find the ceil of a given 
// key in BST
function findCeil(root, key) {
    let ceil = -1;  // -1 indicates no ceiling found yet

    while (root) {
        // If root itself is ceil
        if (root.data === key) {
            return root.data;
        }

        // If root is smaller, the ceil
        // must be in the right subtree
        if (key > root.data) {
            root = root.right;
        } 
        
        // Else either root can be ceil 
        // or a node in the left child
        else {
            ceil = root.data;
            root = root.left;
        }
    }
    return ceil;
}

// Driver code
const root = new Node(8);
root.left = new Node(4);
root.right = new Node(12);
root.left.left = new Node(2);
root.left.right = new Node(6);
root.right.left = new Node(10);
root.right.right = new Node(14);

// Testing for values from 0 to 15
for (let i = 0; i < 16; i++) {
    console.log(findCeil(root, i));
}

Time Complexity: O(lh) where h is height of the given Binary Search Tree 
Auxiliary Space: O(1)  

Exercise:

  1. Modify the above code to find the floor value of the input key in a binary search tree.
  2. Write a neat algorithm to find floor and ceil values in a sorted array. Ensure to handle all possible boundary conditions.

SDE Sheet - Ceil in BST
Article Tags :
Practice Tags :

Similar Reads