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

Ceil Value Node: Node with smallest data larger than or equal to key value.

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.

Here is the code for ceil value.[ad type=”banner”]

Java Program
// Java program to find ceil of a given value in BST

class Node {

int data;
Node left, right;

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

class BinaryTree {

static Node root;

// Function to find ceil of a given input in BST. If input is more
// than the max key in BST, return -1
int Ceil(Node node, int input) {

// Base case
if (node == null) {
return -1;
}

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

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

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

// Driver program to test the above functions
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(8);
tree.root.left = new Node(4);
tree.root.right = new Node(12);
tree.root.left.left = new Node(2);
tree.root.left.right = new Node(6);
tree.root.right.left = new Node(10);
tree.root.right.right = new Node(14);
for (int i = 0; i < 16; i++) {
System.out.println(i + " " + tree.Ceil(root, i));
}
}
}

Output:

0  2
1  2
2  2
3  4
4  4
5  6
6  6
7  8
8  8
9  10
10  10
11  12
12  12
13  14
14  14
15  -1
[ad type=”banner”]

Categorized in: