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:
- Modify the above code to find the floor value of the input key in a binary search tree.
- Write a neat algorithm to find floor and ceil values in a sorted array. Ensure to handle all possible boundary conditions.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem