Learn / Binary search trees

Search, insert and delete

In a binary search tree every value in a node's left subtree is smaller and every value in its right subtree is larger. So search, insert, minimum, maximum and range counts each walk one path from the root: O(h), which is O(log n) when the tree is balanced. Deleting a node with two children replaces it with its inorder successor.

How to recognise it

  • The data is a BST, or must be kept sorted while values are added and removed.
  • Finding, inserting or deleting a value faster than scanning everything.
  • Questions about values in a range, the smallest or the largest.

One path down

831016144713
Searching for 7: 7 < 8 go left, 7 > 3 go right, 7 > 6 go right, found. Inorder gives 1 3 4 6 7 8 10 13 14, sorted.

The rule that makes a BST, and how it compares with a heap, is on the Structures page.

TaskWalk
searchgo left when smaller, right when larger
insertsearch until an empty spot; put the value there
min / maxfar left / far right
count in [l, h]skip a whole subtree when its values are all outside
build from preordereach value goes into the range left by its ancestors

Deleting

  1. No children: remove the node.
  2. One child: the child takes its place.
  3. Two children: copy in the inorder successor (the far left of the right subtree), then delete that value from the right subtree, which is case 1 or 2.

Balance

All of these are O(h). Sorted inserts make h = n. Rebuilding from the sorted inorder by always choosing the middle as the root gives a tree of height about log n.

Common mistakes

  • Comparing with only the parent when validating or inserting; the rule covers whole subtrees.
  • Forgetting the two-children case when deleting.

Problems

0 of 9 solved

Check yourself

Searching for 7 in the pictured BST, which nodes are visited?

Where is the smallest value of a BST?

Deleting a node with two children, what replaces its value?

Why does a BST of n values sometimes take O(n) per search?