Transcript
Here's a tree where every number knows its place: smaller ones to the left, bigger ones to the right. Finding any number takes just a few steps. But feed it numbers in the wrong order, and it grows into a long stick. Today: binary search trees, and how they stay balanced.
The rule: for every node, everything on its left side is smaller, and everything on its right side is bigger. To find six, start at the root. Six is less than eight: go left. More than four: go right. Three steps, and there it is. It's binary search from episode five, built right into the shape of the tree. Adding a number works the same way: walk down until you reach an empty spot, and put it there.
Remember inorder from last time? Walk this tree that way, and the numbers come out sorted, smallest to largest.
But the shape depends on the order you add things. Add one, two, three, all the way to seven, and every number goes to the right. Now the tree is a stick, seven deep. Finding seven takes seven steps, no better than a plain list.
The fix is called a rotation. Take three nodes in a line, lift the middle one up, and let the other two hang on either side. Left to right, the order never changes, so the tree is still sorted. It's just shorter. Three more rotations, and the stick becomes a tree three deep. Finding seven now takes three steps, not seven. Self-balancing trees, like AVL trees and red-black trees, do these rotations for you, every time you add something.
A binary search tree keeps everything sorted as you add it. Keep it balanced, and every search is a short walk down, about log n steps. Next time: why databases use trees that are short and wide, because hard drives hate long walks. See you there.
Next episode: B-trees, and why databases use trees that are short and wide.