## Find ‘ceil’ of a key in a Binary Search Tree (BST)

Long long time, eh?! But it has been a busy time at work. 🙂

So lets solve this problem. An example tree follows:

Now lets say you have the following queries –

**q = 13, Answer = Does Not Exist**

**q = 5, Answer = 6**

How do you go about finding the ceil?

One way to do it is **Inorder Traversal** of the tree. This will take O(n) time and then get you kicked out of the interview. Did you not read “BST” ? So we should be using that particular property of the tree!

Here is the algorithm you should be following in short

“Start with the root as current node.

If value(current node) == key, you are done!

If value(current node) > key, make answer = value(current node) and current node = leftNode(current node).

Else if value(current node)<key, make current node = rightNode(currentNode).

You have your answer once you exhaust nodes in the path you are moving on this fashion. If no value was assigned to answer, this indicates you kept moving right throughout and the tree has no value >= key.”

That does not sound right? Well, try it out for yourself! And the complexity? **O(log n)**. Whoopie!

Actually the complexity is not O(logn). It’s O(height of the tree) where height of the tree could easily be “n”.