class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if root is None:
return Node(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def floor_ceil_bst(root, target):
floor = None
ceil = None
curr = root
while curr:
if curr.val == target:
floor = curr.val
ceil = curr.val
break
elif target < curr.val:
ceil = curr.val # update ceil to current node
curr = curr.left # move left to find smaller or equal
else:
floor = curr.val # update floor to current node
curr = curr.right # move right to find bigger or equal
return floor, ceil
# Driver code
root = None
for v in [8,4,12,2,6,10,14]:
root = insert(root, v)
floor_val, ceil_val = floor_ceil_bst(root, 5)
print(f"Floor: {floor_val}, Ceil: {ceil_val}")loop through nodes until no more to check
exact match found, floor and ceil are target
target less than current, update ceil and go left
ceil = curr.val # update ceil to current node
record current node as possible ceil
curr = curr.left # move left to find smaller or equal
go left to find closer floor or ceil
target greater than current, update floor and go right
floor = curr.val # update floor to current node
record current node as possible floor
curr = curr.right # move right to find bigger or equal
go right to find closer floor or ceil