edubun
English
1 / 21

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 questions

You 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.

  1. const leaf = (k) => ({ key: k, left: null, right: null });
  2. const T = { key: 50, left: { key: 30, left: leaf(20), right: leaf(40) }, right: leaf(70) };
  3. const out = [];
  4. function inorder(n) {
  5. if (n === null) return;
  6. inorder(n.left);
  7. out.push(n.key);
  8. inorder(n.right);
  9. }
  10. inorder(T);
  11. console.log(out.join(" "));
Variables
Output
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.

  1. 30
  2. 70
  3. 40
  4. 50
  5. 20
Hint

Left, node, right.

Solution

Answer:

  1. 20
  2. 30
  3. 40
  4. 50
  5. 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.

Expected output
20 30 40 50 60 70 80
Your code
function 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.

Expected output
3
3
2
Your code
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 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

Mistake
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(" "));
Output
70 50 30
Fixed
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 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(" "));
Output
30 50 70

Smaller 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.

Next unitChoosing a data structure
Full text · The whole lesson as one text

Binary search, built into the shape

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.

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.

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.

A binary search tree. Choose a key and insert or search; the path lights up and the counter shows comparisons. Change the starting tree to "sorted input" to see the same seven keys form a long chain.

Height is everything

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.

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.

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.

Keys in order for free

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.

Key points
  • 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.

Practice questions from Binary search trees on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append)
  • 4 Hashing (chaining, pigeonhole collisions, chain length n/m)
  • 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1)
  • Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262)
  • 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements")
  • Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18