DSAVisualiseData Structures & Algorithms Studio
Trees & Ordered Maps Hard

BST Ceiling Lookup

Build a binary search tree by inserting keys in order, then trace the source's tail-recursive search for the smallest key at least the target.

Trace input

Bounded JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

Source scenarios

Complexity

BestO(1) search after construction when the root is an exact match
AverageO(h) search, where h is tree height
WorstO(n) search in a skewed tree; O(n²) insertion for sorted keys
SpaceO(n) tree plus O(h) Java recursion during tree construction and tail calls

Array state

Follow the active comparisons and writes.

Live snapshot

Current operation

Trace state
Ready to explore
Source behavior & common mistakes

Follow duplicate-left insertion, each tail call, and the currentBest candidate until an exact match or empty subtree returns the answer.

  • An exact key returns immediately, even if a candidate was recorded earlier.
  • When a key is above the target, the source keeps the smaller candidate and searches left.
  • When a key is below the target, the source searches right without changing currentBest.
  • BSTNode.add sends equal keys left because only strictly greater keys go right.
  • If the search reaches null before finding a candidate, ceil returns null.

Algorithm code

Java
BinarySearchTree.javaStep linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1
Comparisons 0