Skip to lesson

Floor, ceiling and LCA in a BST

Binary search tree ordering simplifies finding nearest values, common ancestors, and range boundaries.

Floor and ceiling search in a BST

The floor of a value is the largest key in the tree that is less than or equal to it. The ceiling is the smallest key that is greater than or equal to it.

The floor of a target key is the largest value less than or equal to target. The ceiling of a target key is the smallest value greater than or equal to target.

Example 1 · Brute force: scan the sorted inorder list (O(n) time, O(n) space)

FloorBruteDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class FloorBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    static void inorder(TreeNode node, List<Integer> out) {        if (node == null) return;        inorder(node.left, out);        out.add(node.val);        inorder(node.right, out);    }
    static Integer floor(TreeNode root, int target) {        List<Integer> values = new ArrayList<>();        inorder(root, values);        Integer best = null;        for (int x : values) {            if (x <= target) best = x;        }        return best;    }
    static Integer ceil(TreeNode root, int target) {        List<Integer> values = new ArrayList<>();        inorder(root, values);        for (int x : values) {            if (x >= target) return x;        }        return null;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(8);        root.left = new TreeNode(4);        root.right = new TreeNode(12);        root.left.left = new TreeNode(2);        root.left.right = new TreeNode(6);        root.right.left = new TreeNode(10);        root.right.right = new TreeNode(14);
        System.out.println("Floor of 5: " + floor(root, 5));        System.out.println("Ceil of 5: " + ceil(root, 5));    }}
Output
Floor of 5: 4
Ceil of 5: 6

What this code does

  • Inorder visits the keys in sorted order, so the floor is the last key not above the target and the ceiling is the first key not below it.
  • This ignores the BST shape: it visits and stores all n keys, then scans them.

Example 2 · Optimal: walk one path down the tree (O(h) time, O(1) space)

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static Integer findFloor(TreeNode root, int target) {        Integer floor = null;        TreeNode curr = root;        while (curr != null) {            if (curr.val == target) return curr.val;            if (curr.val < target) {                floor = curr.val;                curr = curr.right;            } else {                curr = curr.left;            }        }        return floor;    }
    static Integer findCeil(TreeNode root, int target) {        Integer ceil = null;        TreeNode curr = root;        while (curr != null) {            if (curr.val == target) return curr.val;            if (curr.val > target) {                ceil = curr.val;                curr = curr.left;            } else {                curr = curr.right;            }        }        return ceil;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(8);        root.left = new TreeNode(4);        root.right = new TreeNode(12);        root.left.left = new TreeNode(2);        root.left.right = new TreeNode(6);        root.right.left = new TreeNode(10);        root.right.right = new TreeNode(14);
        System.out.println("Floor of 5: " + findFloor(root, 5));        System.out.println("Ceil of 5: " + findCeil(root, 5));    }}
Output
Floor of 5: 4
Ceil of 5: 6

What this code does

  • Candidate floor updates whenever the current value is less than target.
  • Candidate ceiling updates whenever the current value is greater than target.
  • Both routines descend along a single tree path in O(h) time.
  • Why it is faster: every comparison discards a whole subtree, so only the nodes on one root-to-leaf path are looked at and nothing is stored.

A brute-force search collects all keys into an array and scans linearly in O(n) time. A binary search tree finds floor and ceiling in O(h) time by comparing values at each step. To find the floor, if node value matches target, return it. If target is smaller than node value, the floor must reside in the left subtree. If target is larger, the current node is a candidate floor. Recurse right to search for a larger candidate, keeping the current node if right returns null.

Lowest common ancestor using BST values

In a general binary tree, finding the lowest common ancestor requires visiting both child subtrees. In a binary search tree, node values tell us exactly which branch contains targets.

Example 3 · BST Lowest Common Ancestor

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static TreeNode lcaBST(TreeNode root, int p, int q) {        TreeNode curr = root;        while (curr != null) {            if (p < curr.val && q < curr.val) {                curr = curr.left;            } else if (p > curr.val && q > curr.val) {                curr = curr.right;            } else {                return curr;            }        }        return null;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(6);        root.left = new TreeNode(2);        root.right = new TreeNode(8);        root.left.left = new TreeNode(0);        root.left.right = new TreeNode(4);        root.left.right.left = new TreeNode(3);        root.left.right.right = new TreeNode(5);
        TreeNode lca1 = lcaBST(root, 2, 8);        System.out.println("LCA of 2 and 8: " + lca1.val);
        TreeNode lca2 = lcaBST(root, 2, 4);        System.out.println("LCA of 2 and 4: " + lca2.val);    }}
Output
LCA of 2 and 8: 6
LCA of 2 and 4: 2

What this code does

  • Both targets less than current value indicates the ancestor lies to the left.
  • Both targets greater than current value indicates the ancestor lies to the right.
  • The split point identifies the lowest common ancestor in O(h) time.

If both target values are smaller than the current node, search left. If both target values are larger than the current node, search right. If target values diverge with one smaller and one larger, the current node is the ancestor. One target lies left and the other lies right, so they split here. This algorithm runs in O(h) time without requiring extra data structures.

Efficient range queries with tree pruning

Range queries collect or sum all tree nodes falling between low and high bounds. Instead of traversing all n nodes, we prune subtrees outside the query interval.

Example 4 · Pruned Range Sum

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static int rangeSumBST(TreeNode root, int low, int high) {        if (root == null) return 0;        if (root.val < low) {            return rangeSumBST(root.right, low, high);        }        if (root.val > high) {            return rangeSumBST(root.left, low, high);        }        return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(10);        root.left = new TreeNode(5);        root.right = new TreeNode(15);        root.left.left = new TreeNode(3);        root.left.right = new TreeNode(7);        root.right.right = new TreeNode(18);
        System.out.println("Range sum [7, 15]: " + rangeSumBST(root, 7, 15));    }}
Output
Range sum [7, 15]: 32

What this code does

  • Prune entire left subtree when the node value is strictly less than low.
  • Prune entire right subtree when the node value is strictly greater than high.
  • Only nodes within or overlapping the query interval are visited.

If the current node value is strictly less than low, discard the entire left subtree. If the current node value is strictly greater than high, discard the entire right subtree. Only visit child subtrees that can potentially contain values inside the range.

Next step

Check your understanding

10 quick questions