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.
| Problem | Is the ceil of |
|---|---|
| inorder successor of p | p.val, strictly greater |
| least greater element to the right | the new value, in a BST of everything to its right |
| populate successors | the 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
- Floor and Ceil in a BSTmediumguide ready
- Inorder Successor in BSTmediumguide ready
- Populate Inorder successor of all nodesmediumguide ready
- Replace every element with the least greater element on its rightmediumguide ready