I've been struggling with a code problem where I have to find the floor and the ceiling of a given number in a binary search tree. For example, 5 is given, so the program should print 4 for floor and 6 for ceiling if they exist. Otherwise, it should print None for each of them.
Here is a sample code to explain:
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def findCeilingFloor(root_node, k, floor=None, ceil=None):
# Fill this in.
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)
print findCeilingFloor(root, 5)
# (4, 6)
I implemented some code for the findCeilingFloor function. Although it finds and assigns the floor and the ceiling values, when the program turns back to the node which contains 12 as the value, it changes the floor and the ceiling value to None again. Therefore, it always returns None for both of them. I added some print statements to keep track what's going on.
Here is my output:
And here is my implementation:
def findCeilingFloor(root_node, k, floor=None, ceil=None):
# Fill this in.
print(f"Current node value = {root_node.value}")
print(f"Floor value = {floor}")
print(f"Ceil value = {ceil}")
print()
if root_node.value == k - 1:
floor = root_node.value
if root_node.value == k + 1:
ceil = root_node.value
if root_node.left:
findCeilingFloor(root_node.left, k, floor, ceil)
if root_node.right:
findCeilingFloor(root_node.right, k, floor, ceil)
return floor, ceil
I didn't understand why my code returns None for both of them even though it finds both the floor and the ceil values(the ceil value doesn't appear on the output because it prints right before it assigns the ceil, I checked that if it finds the ceil as well). When there is no node left to go at the left subtree, it directs to the right subtree, to 12, and then both the floor and the ceil becomes None.