All pages 6 of 8
The search tree
A guessing game made into a shape: at each number you go left for smaller and right for bigger.
Counted: 3 steps
The steps
- 7 is less than 8, so go left.
- 7 is more than 3, so go right.
- 7 is more than 6, so go right, but there is nothing there.
- 7 is not here: 3 steps.
What it is
Think of the game where a friend picks a number and you guess. After each guess they say higher or lower. A good guess throws away half of what is left.
A search tree keeps numbers so that every find plays that game. Each number sits in a node with room for two children. Smaller numbers go on the left and bigger ones on the right. The top node is called the root.
How a move works
Put in 8, 3, 10, 1, 6 and 14, in that order. To find 6, start at 8. 6 is less than 8, so go left to 3. 6 is more than 3, so go right, and there is 6. That is 3 steps.
To find 7, take the same path. At 6, 7 is more, so go right, but there is nothing there. So 7 is not in the tree, and you know it after 3 steps.
Putting a number in works the same way. Walk down as if you were looking for it, and write it in the empty place where the walk ends.
Where you meet it
Search trees keep things in order while they change: the names in a phone book app, the dates in a calendar, the words in a dictionary. Many big stores of data use a cousin of this tree to find things fast.
Watch out for
Put in 1, 2, 3, 4 and 5 in order, and each number goes to the right of the last. The tree grows into a line, 5 levels tall. A find for 5 then costs 5 steps, as slow as walking a list. Real search trees fix this by turning bits of themselves to stay bushy.