Binary Search Tree — Data Structures

A BST (binary search tree) is a binary tree with one rule at every node: all the values on its left are smaller than that node, and all the values on its…

I'm thinking of a number from 1 to 100. You guess, and I only answer "smaller" or "bigger". The smartest first guess is 50: whatever I answer, half the possibilities are gone right away. Seven guesses at most, and you've found it.

A binary search tree (BST) stores data so it can be searched in the same way. It's a binary tree with one rule: for every node, all the values in its left subtree are smaller than that node, and all the values in its right subtree are bigger (or equal). So every node works like one guess: a value smaller than that node is looked for on the left, a bigger one on the right. Everything a BST can do comes from this rule.

The rule: smaller on the left, bigger on the right

This code makes a BST, then fills it with eight numbers:

class TreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BST {
  constructor() {
    this.root = null;
  }

  insert(value) {
    const node = new TreeNode(value);
    if (this.root === null) {
      this.root = node;
      return;
    }
    let current = this.root;
    while (true) {
      if (value < current.value) {
        if (current.left === null) {
          current.left = node;
          return;
        }
        current = current.left;
      } else {
        if (current.right === null) {
          current.right = node;
          return;
        }
        current = current.right;
      }
    }
  }
}

const bst = new BST();
[8, 3, 10, 1, 6, 14, 4, 7].forEach((v) => bst.insert(v));

//         8
//       /   \
//      3     10
//     / \      \
//    1   6      14
//       / \
//      4   7

console.log(bst.root.value);            // 8
console.log(bst.root.left.value);       // 3
console.log(bst.root.left.right.value); // 6

For example, insert(7) into the tree that already holds 8, 3, 10, 1, 6, 14, 4:

Step Compared with Then
1 8 7 is smaller, go left
2 3 7 is bigger, go right
3 6 7 is bigger, go right
4 6's right is still null 7 is placed on the right of 6

Check the rule on that tree: every value in the left subtree of 8 (3, 1, 6, 4, 7) is smaller than 8, and every value in its right subtree (10, 14) is bigger. The same holds for every node. As a result, the smallest number is always the leftmost node (1), and the biggest is the rightmost node (14).

Searching: down one path only

This is the function search:

function search(node, value) {
  while (node !== null) {
    if (value === node.value) return node;
    if (value < node.value) {
      node = node.left;
    } else {
      node = node.right;
    }
  }
  return null;
}

console.log(search(bst.root, 6).value); // 6
console.log(search(bst.root, 5));       // null

This code uses bst from the previous section. Searching works just like insert: compare, then go down to the left or the right.

The return node inside the loop is only used when the value is found. The "not found" answer (return null) can only be given after the loop, once node has become null.

Why it's fast, and when it gets slow

Every step goes down one level, and the subtree on the other side never has to be checked. In a balanced tree, 1,000 items take about 10 steps, and a million items about 20 steps. That's O(log n): with twice the data, the steps only go up by one.

But the shape of the tree depends on the order of the inserts. If the data goes in already sorted, say 1, 2, 3, 4, 5, 6, 7, every new value always goes right, and the tree becomes one-sided: every node has only a right child, like a linked list. Searching for 7 means passing through 7 nodes. That's O(n): twice the data, twice the time. Real-world BSTs (AVL, Red-Black) balance themselves so this doesn't happen.

In-order: sorted for free

In-order is a way to visit every node: the left subtree first, then the node itself, then the right subtree. Because of the BST rule, the result always comes out sorted from small to large:

function inOrder(node, result = []) {
  if (node === null) return result;
  inOrder(node.left, result);
  result.push(node.value);
  inOrder(node.right, result);
  return result;
}

console.log(inOrder(bst.root)); // [1, 3, 4, 6, 7, 8, 10, 14]

inOrder calls itself (recursion), and every call fills the same array, result. Whatever order the values were inserted in, as long as the rule is kept, a BST's in-order always gives the values sorted.

Deleting a node is the hardest BST operation, because the rule must still hold afterwards. First find the node, then count its children:

remove(node, value) deletes value from the subtree that starts at node, then returns the node that is now in that place: node itself, or the one that replaced it. The caller stores that result back in left, right or bst.root:

function remove(node, value) {
  if (node === null) return null; // the value is not there
  if (value < node.value) {
    node.left = remove(node.left, value);
  } else if (value > node.value) {
    node.right = remove(node.right, value);
  } else {
    if (node.left === null) return node.right; // 0 or 1 child
    if (node.right === null) return node.left;
    let next = node.right; // 2 children: find the smallest on the right
    while (next.left !== null) next = next.left;
    node.value = next.value;
    node.right = remove(node.right, next.value);
  }
  return node;
}

bst.root = remove(bst.root, 3);
console.log(bst.root.left.value); // 4
console.log(inOrder(bst.root));   // [1, 4, 6, 7, 8, 10, 14]

After 3 is deleted, 4 moves up to where 3 was, and in-order is still sorted. Like searching, deleting goes down one path: O(log n) in a balanced tree, O(n) in a one-sided one.

⚠️ A search that stops too soon, or never stops

💡 A BST or a hash map? A hash map answers "is it there?" in O(1) on average, faster than a BST. But what's inside a hash map isn't in order. A balanced BST stays at O(log n) and keeps the data in order, so it suits "get the smallest value", "every value between 10 and 50", or a list that must always stay sorted.

TL;DR: A BST (binary search tree) is a binary tree with one rule at every node: all the values on its left are smaller than that node, and all the values on its right are bigger (or equal). Insert (add) and search (find) both start at the root (the top node), compare, then go down left or right. Search stops when it finds the value. When insert or search reaches null (no node), insert places the new node there, and search answers "not found" after the loop. In a balanced tree (one that grows wide), a search is O(log n): 1,000 items in about 10 steps. Data that goes in already sorted makes the tree one-sided, like a linked list: O(n). The smallest number is the leftmost node, and in-order (left, then the node, then right) always gives the values sorted.

⚡ Smaller on the left, bigger on the right

Write:

const bst = new BST();
[8, 3, 10, 1, 6, 14, 4, 7].forEach((v) => bst.insert(v));

console.log(bst.root.value);      // 8
console.log(bst.root.left.value); // 3

Meaning: BST is a class (a blueprint for objects) for a binary search tree, and new BST() makes an empty tree. forEach calls insert for each number. The first value becomes the root (the top node). Every value after it goes down from the root: smaller goes left, bigger (or equal) goes right, until it finds a spot that's still null (empty). The rule holds at every node.

⚡ Searching: down one path

Write:

while (node !== null) {
  if (value === node.value) return node;
  if (value < node.value) {
    node = node.left;
  } else {
    node = node.right;
  }
}
return null;
Guess first: the tree from the step before holds 8 nodes, with 8 at the root and 3 on its left. If you search for 6, how many nodes are checked?

Only 3: 8, then 3, then 6 is found. Every step goes down one level, and the other side is never checked.

Meaning: node is the node being checked, starting at the root, and value is the value you're looking for. The "not found" answer (return null) comes only after the loop, once node is null. In a balanced tree, a search is O(log n). Data that goes in already sorted makes the tree one-sided, like a linked list: O(n).

⚡ In-order is always sorted

Meaning: In-order is a way to visit every node: the left subtree (the left child and all the nodes below it) first, then the node itself, then the right subtree. Because of the BST rule, the result always comes out sorted from small to large. For the tree in the first step: [1, 3, 4, 6, 7, 8, 10, 14].

What you will learn