Learn / Binary search trees

Floor and ceil

The floor of x is the largest value at most x; the ceil is the smallest value at least x. Walk down from the root: a value below x is a floor candidate (go right for a bigger one), a value above x is a ceil candidate (go left for a smaller one). The inorder successor of a node is the ceil of a value just above it.

How to recognise it

  • The closest value above or below a key.
  • The next node in sorted order.
  • For each element, the least greater element after it.

One walk, two candidates

floor = ceil = none
n = root
while n:
    if n.val == x: return (x, x)
    if n.val < x: floor = n.val; n = n.right
    else: ceil = n.val; n = n.left

The rule that makes a BST, and how it compares with a heap, is on the Structures page.

ProblemIs the ceil of
inorder successor of pp.val, strictly greater
least greater element to the rightthe new value, in a BST of everything to its right
populate successorsthe previous node in a reverse inorder walk

Common mistakes

  • Returning the parent instead of the best candidate seen.
  • Treating an equal value as the successor.

Problems

0 of 4 solved

Check yourself

BST [8, 4, 12, 2, 6, 10, 14], key 11. Floor and ceil?

When the walk meets a value smaller than the key, which way does it go?

Building a BST from the right of an array, why does it give the least greater element?