Data Structures19 sections · 729 units
Open in Course

Floor and Ceiling

Find closest values

Floor is the largest element x\leq x. Ceiling is the smallest element x\geq x.

def floor(root, x):
    result = null
    while root:
        if root.val == x:
            return root.val
        if root.val < x:
            result = root.val
            root = root.right
        else:
            root = root.left
    return result

def ceiling(root, x):
    result = null
    while root:
        if root.val == x:
            return root.val
        if root.val > x:
            result = root.val
            root = root.left
        else:
            root = root.right
    return result

Time: O(h)O(h). These operations are common in BST-based maps for range queries.