Binary search trees

Smaller on the left, larger on the right · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Binary search tree

A binary search tree follows a rule at every node: every value in its left subtree is smaller than it, and every value in its right subtree is larger. And the rule also holds inside each subtree. Thanks to that, looking at a single node already tells you which way what you're after is, just like binary search.

To search for a value, you start at the root and compare: if the node is smaller than what you want, go right; if larger, go left; if equal, found. Each step discards a whole subtree, just as binary search discards half. The number of steps is at most the tree's height: in a balanced one, O(log n).

To insert a value, you go down the tree as if searching for it, until landing on an empty spot, past a leaf. There the new node is created. While going down, you remember the last node visited, which will be the parent. If the value is already in the tree, it isn't inserted, because duplicates break the rule. It costs the same as searching: O(log n) if balanced.

Deleting depends on how many children the node has. If it has none, it's a leaf and is removed directly. If it has 1 child, that child takes its place. If it has 2, it can't simply be removed: it's replaced by the next one in order, which is the smallest in its right subtree, and then that replacement is deleted from where it was. That way the smaller-and-larger rule is kept.

Inorder traversal visits left, root, right. Since in a search tree smaller values are on the left and larger on the right, inorder always visits the next smallest value. Result: a search tree's inorder comes out sorted from smallest to largest, in O(n), without sorting separately.

Compared with an unsorted array, a balanced search tree wins at searching and deleting: O(log n) against O(n). The array wins at inserting at the end, O(1). But the tree only pays off if it's balanced: with lots of inserting and deleting, or inserting already sorted values, it leans and goes back to O(n). It's used for multi-level indexes, for keeping data sorted as it arrives, and as the base for self-balancing trees.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Smaller on the left, larger on the right