1 of 4

Your RightSignal

Data structures · 6 of 111 / 3

Binary trees

The concept

How to add a name to a sorted list without shifting all the others

A binary search tree keeps items sorted and cheap to add to. Each node (a record with a key and two links) has at most two children: smaller keys go in its left branch, larger keys in its right.

Take keys 50, 30, 70, 20, 40, 60, 80, with 50 as the root (top node). To add 45, a sorted array must shift every later item. The tree walks down and hangs 45 as a new leaf (a node with no children); nothing moves.

Reading the tree left branch, then node, then right branch (an in-order walk) gives 20, 30, 40, 45, 50, 60, 70, 80, the keys in sorted order.

What it’s forGives the most comparisons a search needs in a perfectly balanced binary tree.

max comparisons = h + 1 = log₂(n + 1)

h
the tree's height: links from the root down to the deepest leaf
n
the number of keys in the tree, e.g. 7 or 1,048,575

What it givesHow many nodes a lookup or insert touches on its way down, which grows only with the logarithm of n.

  1. 7 keys: log₂(8) = 3 comparisons
  2. 1,023 keys: log₂(1,024) = 10 comparisons
  3. 1,048,575 keys: log₂(1,048,576) = 20 comparisons