19/06/2021

[Java] Find floor and ceil of binary search tree item

Given a BST and a value, find the floor and ceil items in the tree for it.

If item is in the tree, floor and ceil are the item itself, otherwise they are the closest smallest and largest values in the tree. If floor or ceil do NOT exist for an item, return them as MIN or MAX int.

Example:


                      8
                   4    12
                 2  6  10 14

For this tree, item 4 is in the tree, so floor and ceil = 4

Item 1 however is NOT in the tree, it would be a left child of item 2, so floor and ceil are MIN, 2

Item 5 is NOT in the tree but we have 4 and 6 as floor and ceil for it.

We can use a recursive DFS approach to scan the tree testing each node on our path to the correct location of the item we are searching for.

We start with floor = MIN and ceil = MAX int and we update our boundaries as we traverse the tree.

Worst case our tree is a single branch of increasing or decreasing elements, and our element is the largest or smallest NOT in the tree, therefore complexity is O(N) time and space.

You can check my implementation of findFloorAndCeil on my Gist along with some tests in FindFloorAndCeilJTests.

No comments:

Post a Comment

With great power comes great responsibility