Description
Bisect on a BST finds the boundary near a target instead of an exact hit. Same idea as Bisect Left-Right, but you walk the tree instead of indexing an array.
?
Reach for when
You want the closest value to a target in a BST (floor/ceiling/next/prev) not necessarily an exact match.
Runtime
balanced: O(log(n))
unbalanced: O(n)
Visualization
%20Bisect%20Left-Right-1784011154177.webp)
Pseudocode
Ceiling(node, target): # smallest value >= target
best = null
while node:
if node.value < target: # too small → go right
node = node.right
else: # candidate → record, go left
best = node.value
node = node.left
return best
# floor / bisect_right: swap < for <=
Code
def bisect_left_bst(root, target): # smallest value >= target (ceiling)
best = None
node = root
while node:
if node.val < target: # too small → go right
node = node.right
else: # >= target → candidate, go left
best = node.val
node = node.left
return best