High interview relevanceRoadmap: Intermediate
TimeSearch, insert, delete O(h): O(log n) balanced, O(n) worst case
SpaceO(n)

Why it costs this much

Each comparison discards one subtree, so a lookup follows a single root-to-leaf path of length at most h.

Code

def search(node, key):
    while node:
        if key == node.key:
            return node
        node = node.left if key < node.key else node.right   # one step per level
    return None    # at most h steps, where h is the tree height

Common pitfalls

Inserting sorted keys into a plain BST builds a chain, so h equals n and every operation is O(n). Balanced trees prevent this.

Operation by operation

OperationBestAverageWorstSpace
Binary search tree search, insert, deleteO(1)O(log n)O(n)O(1) iterative; O(h) recursive

Binary search tree search, insert, delete. Average assumes keys inserted in random order. Cost is O(h) for tree height h. Inserting sorted keys makes the tree a chain, and every operation O(n).

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list