Skip to content
← Notes

Lesson 02 · Data structures · 13 min

Binary search trees

Build the tree from my notebook one number at a time, search it, then break it by feeding it sorted input.

My handwritten notes: Array representation and a binary search tree built from 13 numbers

After this you can

  • Insert, search and delete in a BST by hand and in code
  • Explain why an infix walk of a BST comes out sorted
  • Spot the input that turns a tree into a list, and know what real systems do about it

My page defines it in one line: a binary search tree is a binary tree where everything to the left of a node is smaller and everything to the right is bigger. Below that I built one by hand from thirteen numbers: 40, 30, 44, 28, 76, 65, 47, 66, 56, 39, 4, 10, 8. There's a first attempt scribbled out on the left and a cleaner one on the right.

That one rule buys you something big. At every node you know which half the thing you want is in, so each comparison throws away a whole subtree. It's binary search, but on a structure you can keep adding to.

Build it yourself

To insert, start at the root and keep going left if the new number is smaller or right if it's bigger, until you fall off the tree. That empty spot is where it goes. Searching is the same walk; you either land on the number or fall off and know it isn't there.

40

Insert the next number from my page, or type your own.

Nodes
1
Height
0
Compares
–

infix → 40

Every comparison throws away a whole subtree. That's the point of the tree, and it only works while the tree stays bushy: feed it sorted numbers and it becomes a linked list.

Try searching for 39, then 50. Finding 39 takes three comparisons (40, 30, 39). Proving 50 isn't there takes six, all the way down to 56. Nothing like scanning thirteen numbers one by one.

Why infix comes out sorted

Infix visits the left subtree, then the node, then the right subtree. In a BST the left subtree holds exactly the smaller values and the right holds the bigger ones. Apply that at every node and the output can only be in order. That makes a BST a sorting machine too: insert everything, then read it back in infix. Done right, that's about n log n work, the same as the good sorting algorithms. The traversal lesson has the walk itself.

Insert, search, delete

bst.pypython
class Node:    def __init__(self, key):        self.key, self.left, self.right = key, None, Nonedef insert(root, key):    if root is None:        return Node(key)    if key < root.key:        root.left = insert(root.left, key)    elif key > root.key:        root.right = insert(root.right, key)    return root                       # equal keys: already theredef search(root, key):    while root:        if key == root.key:            return root        root = root.left if key < root.key else root.right    return Noneroot = Nonefor k in [40, 30, 44, 28, 76, 65, 47, 66, 56, 39, 4, 10, 8]:    root = insert(root, k)

Deleting is the only part with any thought in it. There are three cases:

  • A leaf, like 8: just remove it.
  • One child, like 44 (it only has 76 on its right): the child moves up and takes its place.
  • Two children, like the root 40: replace its key with the smallest key in its right subtree (its in-order successor), then delete that successor from down there. For my tree the successor of 40 is 44, so 44 becomes the root and 76 moves up under it. The successor never has a left child, so removing it is always one of the two easy cases.
deletepython
def delete(root, key):    if root is None:        return None    if key < root.key:        root.left = delete(root.left, key)    elif key > root.key:        root.right = delete(root.right, key)    else:        if root.left is None:          # no children, or only a right child            return root.right        if root.right is None:         # only a left child            return root.left        succ = root.right              # two children: smallest key on the right        while succ.left:            succ = succ.left        root.key = succ.key        root.right = delete(root.right, succ.key)    return root

How fast, really

Every operation walks one path from the root, so its cost is the tree's height h, not the number of keys. In a bushy tree h is about log₂ n: a million keys, about twenty comparisons. My thirteen numbers made a tree of height 5, a little taller than the best possible 3, because of that long chain 40, 30, 28, 4, 10, 8.

Now press Insert 10…70 in order in the playground. Sorted input means every new key is the biggest so far, so it always goes right. The “tree” is a linked list with extra steps, height n − 1, and search is back to checking every key. Sorted data is common in real life (timestamps, IDs, alphabetical names), so this isn't a corner case.

OperationBushy treeDegenerate treeSorted array
SearchO(log n)O(n)O(log n)
InsertO(log n)O(n)O(n), things shift
DeleteO(log n)O(n)O(n)
Everything in orderO(n), infixO(n)O(n)

Real libraries fix this with self-balancing trees, which do a little rearranging (rotations) after each insert or delete to keep the height near log n. AVL trees, from 1962, keep the two sides of every node within one level of each other. Red-black trees are looser and cheaper to maintain, and they sit behind Java's TreeMap and most implementations of C++'s std::map.

Where you'll meet these

  • Database indexes

    An index in PostgreSQL, MySQL or SQLite is usually a B-tree: a search tree where each node holds hundreds of keys, so a lookup reads a handful of disk pages instead of the whole table.

  • Range queries

    “Every transaction between 1 and 15 March” is a search for the first date, then an infix walk until you pass the last one. A hash table can't do that; a search tree does it naturally.

  • Ordered maps and sets

    Leaderboards, timetables, a list of events sorted by time that keeps changing: anything that needs to stay sorted while you insert and delete.

  • Heaps, the cousin

    The array layout at the top of my page (root at 1, children at 2i and 2i + 1) is how binary heaps are stored. A heap is weaker than a BST (it only knows its smallest item), but it's all a priority queue needs.

Try it

01Insert 50 into my tree. Where does it end up, and how many comparisons does it take?

Show the answer
As the left child of 56, after six comparisons: 40 (go right), 44 (right), 76 (left), 65 (left), 47 (right), 56 (left, and that spot is empty).

02In what order should you insert 1 to 7 to get a perfectly balanced tree?

Show the answer
4, then 2 and 6, then 1, 3, 5, 7. Always insert the middle of what's left first. That's also the level order of the finished tree.

03Delete 30 from my tree. What takes its place?

Show the answer
39. 30 has two children, so it takes the smallest key in its right subtree. That subtree is just 39.

04Why can't you binary-search a linked list, even if it's sorted?

Show the answer
Binary search needs to jump to the middle in one step. A linked list makes you walk there, which costs O(n) anyway. A BST stores the middles for you: the root is the middle, its children are the middles of each half, and so on.

Further reading

07 · Contact

Write to me.

I'm open to software engineering and data roles, and to freelance work. If you have a process that still runs on copy and paste, I'd like to hear about it.