Binary search trees
In a binary search tree smaller values go left and larger ones right. The insertion order decides the shape.
Rules
- Left smaller, right larger
- Preorder: root, left, right
- Inorder gives the sorted sequence
Your turn
Three problems on this topic. Separate lists with commas.
- 1 · Binary search tree
- 2
- 3
Insert the numbers one by one into an empty binary search tree.
17, 30, 21, 40, 26, 34
Preorder (comma-separated)
Height (nodes on the longest path)
Separate lists with commas, such as 3, 5, 7. Spaces don’t matter.
Worked example
Insert the numbers one by one into an empty binary search tree.
39, 32, 34, 29, 10, 36
Worked solution
- 1The root is 39, smaller values go left, larger right.
- 2Preorder: 39, 32, 29, 10, 34, 36
- 3Inorder: 10, 29, 32, 34, 36, 39
Typical mistake: The insertion order decides the shape: the first number always stays the root.
Common questions
How bad can a search tree get?
On sorted input it degenerates into a list of height n.
