function insert(root: Node | null, key: number): Node { if (root === null) return { key, left: null, right: null };if (key < root.key) root.left = insert(root.left, key);
else root.right = insert(root.right, key);
return root;
}
function search(root: Node | null, key: number): Node | null {if (root === null || root.key === key) return root;
return key < root.key ? search(root.left, key) : search(root.right, key);
}
function remove(root: Node | null, key: number): Node | null {if (root === null) return null;
if (key < root.key) root.left = remove(root.left, key);
else if (key > root.key) root.right = remove(root.right, key);
else if (root.left === null) return root.right;
else if (root.right === null) return root.left;
else {const successor = minimum(root.right);
root.key = successor.key;
root.right = remove(root.right, successor.key);
}
return root;
}
The tree is empty: 24 becomes the root.
Understanding Binary search tree
The idea
A binary search tree keeps one rule at every node: everything in the left subtree is smaller, everything in the right subtree is larger. Insert and search both walk down from the root, turning left or right after one comparison per level, so the cost of every operation is the height of the tree.
Delete has three cases. A leaf is simply unlinked; a node with one child is replaced by that child; a node with two children takes the key of its in-order successor, the smallest key in its right subtree, and that successor, which has at most one child, is removed instead.
The four stages
Complexity
Versus its siblings
Pseudocode
INSERT(node, key)
if node is null: return a new leaf with key
if key < node.key: node.left ← INSERT(node.left, key) else node.right ← INSERT(node.right, key)
REMOVE(node, key)
descend to the node holding key
no left child: replace it by its right child (also covers a leaf)
no right child: replace it by its left child
two children: copy the successor's key into it, then REMOVE the successor from the right subtree
When to use
Pitfalls
History
Binary search trees appeared independently in several places around 1960; Windley, Booth and Colin, and Hibbard each published versions. Hibbard's 1962 paper gave the deletion algorithm shown here and the first analysis of random trees, showing the expected depth is logarithmic.