Data structures›Binary search trees
Tutorial 10 of 13 · Data structures · Trees · BeginnerBinary search trees
Smaller goes left, larger goes right: find a number in a few steps, as long as the tree stays short and wide.
9 lessons, the last is a challenge · about 1 h 30 min · Python and Java
Before you startBinary trees: what a node, a child and a leaf are, and the inorder walk
Recursion: a function that calls itself on a smaller tree
Watch first · about 8 minBinary search trees: the same seven numbers, three steps or seven. The narration uses an AI clone of the creator’s voice.What you’ll be able to do
- 1Say the order rule for whole subtrees, not only for children, and say where any key belongs in a given tree.
- 2Follow a search or an insert down the tree, counting one comparison per level, and say why finding a key takes its depth + 1 comparisons.
- 3Delete a key in all three cases, giving a node with two children the next key in sorted order (its inorder successor).
- 4Explain why sorted input makes a straight chain, why every cost depends on the height, and what a balanced tree guarantees.
- 5Use the inorder walk to list keys in sorted order and to find the keys in a range, and say why it is sorted.
- 6Answer 'BST or hash map?' by asking 'do you need order?', and name what Python and Java give you.
Lessons
- 1The order ruleSay the short rule, and use it to find a number or show that it is not there.7 min, up next
- 2The full rule: whole subtreesSay the rule for whole subtrees, and use it to find the smallest key.10 min
- 3Search follows the ruleFollow a search and count its comparisons: depth + 1 to find a key.13 min
- 4Insert: adding a new keySay where a new key goes and why it always starts as a leaf.12 min
- 5Delete: leaf, one child, two childrenDelete a key in all three cases, using the next key in sorted order.16 min
- 6Why the shape mattersExplain why sorted input makes a chain, what O(log n) means here, and what balanced trees guarantee.12 min
- 7Inorder is sortedUse the inorder walk to list keys in order and to find the keys in a range.12 min
- 8BSTs in practiceChoose between a BST and a hash map, and name TreeMap, TreeSet and bisect.9 min
- 9Final challenge: validate, kth smallest, common ancestorFinal challenge · Check that a tree is a BST, and find the kth smallest key and a lowest common ancestor.10 min
Next in this path
Next: 11 · Heaps and priority queues · 7 lessons · 1 h 21 min
Always get the most urgent item next, even while new items keep arriving.
Playground
Try the same model with your own values. No checks, nothing recorded.
Open the playground