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”] [pastacode lang=”python” manual=”%23%20Python%20program%20to%20find%20ceil%20of%20a%20given%20value%20in%20BST%0A%20%0A%23%20A%20Binary%20tree%20node%0Aclass%20Node%3A%0A%20%20%20%20%20%0A%20%20%20%20%23%20Constructor%20to%20create%20a%20new%20node%0A%20%20%20%20def%20__init__(self%2C%20data)%3A%0A%20%20%20%20%20%20%20%20self.key%20%3D%20data%0A%20%20%20%20%20%20%20%20self.left%20%3D%20None%0A%20%20%20%20%20%20%20%20self.right%20%3D%20None%0A%20%0A%23%20Function%20to%20find%20ceil%20of%20a%20given%20input%20in%20BST.%20If%20input%0A%23%20is%20more%20than%20the%20max%20key%20in%20BST%2C%20return%20-1%0Adef%20ceil(root%2C%20inp)%3A%0A%20%20%20%20%20%0A%20%20%20%20%23%20Base%20Case%0A%20%20%20%20if%20root%20%3D%3D%20None%3A%0A%20%20%20%20%20%20%20%20return%20-1%0A%20%20%20%20%20%0A%20%20%20%20%23%20We%20found%20equal%20key%0A%20%20%20%20if%20root.key%20%3D%3D%20inp%20%3A%0A%20%20%20%20%20%20%20%20return%20root.key%20%0A%20%20%20%20%20%0A%20%20%20%20%23%20If%20root’s%20key%20is%20smaller%2C%20ceil%20must%20be%20in%20right%20subtree%0A%20%20%20%20if%20root.key%20%3C%20inp%3A%0A%20%20%20%20%20%20%20%20return%20ceil(root.right%2C%20inp)%0A%20%20%20%20%20%0A%20%20%20%20%23%20Else%2C%20either%20left%20subtre%20or%20root%20has%20the%20ceil%20value%0A%20%20%20%20val%20%3D%20ceil(root.left%2C%20inp)%0A%20%20%20%20return%20val%20if%20val%20%3E%3D%20inp%20else%20root.key%20%0A%20%0A%23%20Driver%20program%20to%20test%20above%20function%0Aroot%20%3D%20Node(8)%0A%20%0Aroot.left%20%3D%20Node(4)%0Aroot.right%20%3D%20Node(12)%0A%20%0Aroot.left.left%20%3D%20Node(2)%0Aroot.left.right%20%3D%20Node(6)%0A%20%0Aroot.right.left%20%3D%20Node(10)%0Aroot.right.right%20%3D%20Node(14)%0A%20%0Afor%20i%20in%20range(16)%3A%0A%20%20%20%20print%20%22%25d%20%25d%22%20%25(i%2C%20ceil(root%2C%20i))%0A%20″ message=”Python Program” highlight=”” provider=”manual”/]

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: