Codele / Data structures
Binary search trees
Remember the guess-my-number game: “higher” or “lower” throws away half the numbers. A tree can be built so that every question does exactly that.
- In a binary search tree, smaller numbers hang to the left of a number and bigger numbers to the right. “Binary” means each number has at most two children.
- To search, compare at each number. Smaller: go left. Bigger: go right. Same: found. An empty spot means the number is not in the tree.
- Every step throws away about half of what is left, like the guess-my-number game.
- To add a number, make the same walk. The empty spot where the search would end is where the new number hangs.
- A neat, balanced tree is fast. A lopsided one, built from numbers already in order, is not much better than a list.
Loading the playable lesson…