6 / 7 · Intermediate
Binary search trees
A perfectly balanced search tree of 1,023 keys needs at most 10 comparisons. Here, perfectly balanced means every level is full. Inserting sorted keys without rebalancing can instead require 1,023 comparisons.
Jump to the 10 practice questionsYou will learn
- Search and insert by going left or right
- Relate the cost of a search to the height of the tree
Before this: Hash tables
1Explain
Order and fast lookups
Binary search on a sorted array finds a key in about log₂ n checks, but inserting into a sorted array moves values. A hash table inserts quickly, but it forgets order: it cannot easily tell you the smallest key or the next key after 40. A binary search tree (BST) aims for both. It is made of nodes, like a linked list, but each node has two pointers, left and right. The top node is the root; a node with no children is a leaf.
2Explore
The search tree rule
One rule makes it a search tree: for every node, all keys in its left subtree are smaller, and all keys in its right subtree are larger. To search for a key, start at the root and compare. Equal means found. Smaller means go left, larger means go right. Each comparison throws away a whole subtree, just as binary search throws away half the list. Searching the tree 50, 30, 70, 20, 40, 60, 80 for 60 compares with 50, then 70, then 60: 3 comparisons.
Pick a key. The yellow nodes are the comparisons made on the way down.
Press a button: each one runs one operation and shows what it cost.
[50,30,70,20,40,60,80]Total steps 0
3Problem
The rule
Which statement is the binary search tree property?
Hint
It holds at every node, not only at the root.
Solution
Answer: Left subtree keys are smaller and right subtree keys are larger, at every node
That ordering is what lets each comparison rule out a whole subtree.
4Problem
Searching for 60
Tree built from 50, 30, 70, 20, 40, 60, 80. How many comparisons does searching for 60 take?
Hint
50, then 70, then 60.
Solution
Answer: 3
50 (go right), 70 (go left), 60 (found).
5Problem
Searching for 45
Same tree: searching for 45, which is missing, takes how many comparisons?
Hint
50, 30, 40, then an empty pointer.
Solution
Answer: 3
50 (left), 30 (right), 40 (right, but empty): 3 comparisons, then stop.
6Explore
Inserting a key
Inserting follows the same path. Go left or right until the pointer you need is empty, and hang the new node there. Inserting 45 compares with 50 (go left), 30 (go right) and 40 (go right), and 40 has no right child, so 45 becomes it. Deleting a node that is not a leaf takes one more idea: MIT's notes swap its item with the next or previous key in order and delete from there instead. The counting rule in the lab is one comparison per node on the path.
insert walks the same path as a search and hangs the new node on the empty pointer at the end.
Press a button: each one runs one operation and shows what it cost.
[50,30,70,20,40,60,80]Total steps 0
7Problem
Where 45 goes
Insert 45 into that tree. Where does it go?
Hint
The path ends at 40, going right.
Solution
Answer: Right child of 40
The search path ends at 40 going right, and that pointer is empty.
8Explain
Height decides the cost
How many comparisons can a search take? At most one per level, so the cost depends on the tree's height, the number of edges on the longest path from the root down to a leaf. MIT's notes put it this way: tree operations run in O(h) time. The tree 50, 30, 70, 20, 40, 60, 80 has height 2, so no search needs more than 3 comparisons. A perfectly balanced tree with 1,023 nodes has height 9 and needs at most 10.
9Problem
The height
What is the height of the tree 50, 30, 70, 20, 40, 60, 80?
Hint
Count edges on the longest path from the root.
Solution
Answer: 2
Root 50, then 30 and 70, then the four leaves: the longest path has 2 edges.
10Explore
Sorted input makes a chain
But the shape depends on insertion order. Insert 10, 20, 30, 40, 50, 60, 70 in sorted order and each key is larger than everything before it, so each new node goes to the right of the last one. The tree becomes a chain of height 6, and searching for 70 takes 7 comparisons: a linked list with extra pointers. With 1,023 sorted keys the worst search takes 1,023 comparisons instead of 10.
Insert the keys in sorted order and watch the tree lean right until it is a chain.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
11Problem
Searching the chain
Insert 10, 20, 30, 40, 50, 60, 70 in that order. How many comparisons does searching for 70 take?
Hint
70 is at the bottom of a chain of 7.
Solution
Answer: 7
Each key went to the right of the previous one, so the tree is a chain of 7 nodes and 70 is at the bottom.
12Problem
A balanced tree of 1,023 keys
A perfectly balanced BST has 1,023 nodes (height 9). What is the most comparisons a search can take?
Hint
One comparison per level: height + 1.
Solution
Answer: 10
One comparison per level: height + 1 = 10. (2¹⁰ − 1 = 1,023.)
13Explain
Balanced trees
Balanced trees fix this by reshaping themselves after each insert or delete. The first scheme was the AVL tree, from Georgy Adelson-Velsky and Evgenii Landis in 1962, which MIT's lecture 7 covers. It keeps, at every node, the heights of the two subtrees within 1 of each other, and repairs any break with small local moves called rotations. That keeps the height O(log n), so search, insert and delete stay O(log n) whatever order the keys arrive in.
14Problem
The first balanced scheme
Who proposed the first balanced tree scheme, and when?
Hint
The AVL tree is named after them.
Solution
Answer: Adelson-Velsky and Landis, 1962
The AVL tree is named after them; MIT 6.006 lecture 7 gives 1962.
15Explain
Keys in order
A BST keeps more than membership. Visit the left subtree, then its root, then the right subtree. Repeat this rule inside each subtree. This repeated use of the same rule is called recursion. The keys come out in sorted order. This in-order walk (MIT calls it traversal order) is how a BST answers "smallest key", "largest key" and "next key after 40", the order operations of MIT's Set interface that a hash table cannot do quickly.
Left subtree, then the node, then the right subtree: the keys come out sorted.
const leaf = (k) => ({ key: k, left: null, right: null });const T = { key: 50, left: { key: 30, left: leaf(20), right: leaf(40) }, right: leaf(70) };const out = [];function inorder(n) {if (n === null) return;inorder(n.left);out.push(n.key);inorder(n.right);}inorder(T);console.log(out.join(" "));
20 30 40 50 70
16Problem
In-order walk
Put the keys of the tree 50, 30, 70, 20, 40 in the order an in-order walk visits them.
- 30
- 70
- 40
- 50
- 20
Hint
Left, node, right.
Solution
Answer:
- 20
- 30
- 40
- 50
- 70
Left subtree, node, right subtree gives sorted order.
17Problem
A question for a tree
Which question can a BST answer quickly but a plain hash table cannot?
Hint
Which one needs the keys in order?
Solution
Answer: What is the next key after 40?
Order operations need the keys in sorted order, which the tree keeps and a hash table scatters.
18Practice
Finish insert
Finish insert. The in-order walk should then print 20 30 40 50 60 70 80.
20 30 40 50 60 70 80function insert(node, k) {
if (node === null) return { key: k, left: null, right: null };
// If k < node.key, set node.left = insert(node.left, k).
// If k > node.key, set node.right = insert(node.right, k).
return node;
}
function inorder(node, out) {
if (node === null) return out;
inorder(node.left, out); out.push(node.key); inorder(node.right, out);
return out;
}
let root = null;
for (const k of [50, 30, 70, 20, 40, 60, 80]) root = insert(root, k);
console.log(inorder(root, []).join(" "));
Hint
Store what the recursive call returns: node.left = insert(node.left, k).
A solution
function insert(node, k) {
if (node === null) return { key: k, left: null, right: null };
if (k < node.key) node.left = insert(node.left, k);
else if (k > node.key) node.right = insert(node.right, k);
return node;
}
function inorder(node, out) {
if (node === null) return out;
inorder(node.left, out); out.push(node.key); inorder(node.right, out);
return out;
}
let root = null;
for (const k of [50, 30, 70, 20, 40, 60, 80]) root = insert(root, k);
console.log(inorder(root, []).join(" "));19Practice
Search and height
Count comparisons in search and finish height. It should print 3, 3 (45 is missing: 50, 30, 40) and 2.
3
3
2const leaf = (k) => ({ key: k, left: null, right: null });
const T = { key: 50, left: { key: 30, left: leaf(20), right: leaf(40) }, right: { key: 70, left: leaf(60), right: leaf(80) } };
function search(node, k) {
let comparisons = 0;
// While node is not null: add 1 to comparisons; if node.key === k return comparisons;
// otherwise move node to node.left or node.right.
return comparisons;
}
function height(node) {
if (node === null) return -1;
return 0; // should be 1 + the larger of the two subtree heights
}
console.log(search(T, 60));
console.log(search(T, 45));
console.log(height(T));
Hint
An empty tree has height -1, so a single node has height 0.
A solution
const leaf = (k) => ({ key: k, left: null, right: null });
const T = { key: 50, left: { key: 30, left: leaf(20), right: leaf(40) }, right: { key: 70, left: leaf(60), right: leaf(80) } };
function search(node, k) {
let comparisons = 0;
while (node !== null) {
comparisons++;
if (node.key === k) return comparisons;
node = k < node.key ? node.left : node.right;
}
return comparisons;
}
function height(node) {
if (node === null) return -1;
return 1 + Math.max(height(node.left), height(node.right));
}
console.log(search(T, 60));
console.log(search(T, 45));
console.log(height(T));20Explain
Common mistakes
function insert(node, k) {
if (node === null) return { key: k, left: null, right: null };
if (k < node.key) node.right = insert(node.right, k);
else node.left = insert(node.left, k);
return node;
}
const out = [];
const walk = (n) => { if (n) { walk(n.left); out.push(n.key); walk(n.right); } };
let root = null;
for (const k of [50, 30, 70]) root = insert(root, k);
walk(root);
console.log(out.join(" "));70 50 30function insert(node, k) {
if (node === null) return { key: k, left: null, right: null };
if (k < node.key) node.left = insert(node.left, k);
else node.right = insert(node.right, k);
return node;
}
const out = [];
const walk = (n) => { if (n) { walk(n.left); out.push(n.key); walk(n.right); } };
let root = null;
for (const k of [50, 30, 70]) root = insert(root, k);
walk(root);
console.log(out.join(" "));30 50 70Smaller keys go left. With the sides swapped the tree still looks fine, but the in-order walk comes out backwards.
21
Summary
- In a BST, smaller keys go left and larger keys go right at every node.
- Search and insert follow one path: at most height + 1 comparisons.
- Sorted input makes a chain (7 keys, height 6); balanced trees like AVL (1962) keep height O(log n).
- An in-order walk lists the keys in sorted order.