data structurestrees
binary search tree
smaller keys go left, bigger go right, so a lookup walks one path down.
every node's left subtree holds smaller keys and its right subtree bigger ones, so a search goes one way at each node, down one level per step.
- search
- O(log n) on average, one node per level
- insert / remove
- O(log n) on average, a walk and a few links
- walk in order
- O(n) the keys come out sorted
- min / max
- O(log n) on average, as far left or right as it goes
- sorted inserts
- O(n) the tree turns into a stick
- sorted maps and sets
- range queries, every key between two values
- floor and ceiling, the nearest key below or above
- ordered iteration
- the base for balanced trees and b-trees
on this page
a binary search tree keeps its keys in order without keeping them in a row. at every node, the smaller keys live in the left subtree and the bigger ones in the right. a search compares at each node and goes one way, so it walks a single path from the root down: about log n nodes when the tree is bushy. the catch is that nothing keeps it bushy.
the idea
an animation in four steps. a tree of seven keys has 50 at the root, 30 and 70 under it, and 20, 40, 60 and 80 below those. first the keys left of 50 are marked cyan and the keys right of it amber. then a search for 60 walks right from 50, left from 70, and finds 60. then 65 is inserted: the same walk falls off on 60's right, 70 and 80 shift over a column, and 65 hangs there. last, every node drops straight down onto one row, where the keys read 20, 30, 40, 50, 60, 65, 70, 80, in order.
the easy part
search starts at the root. equal: found. smaller: go left. bigger: go right. an empty link means the key isn’t there. each step goes down a level, so a search looks at one node per level at most: its cost is the tree’s height, h.
insert is the same walk. where it falls off the tree is the only place the new key can go and keep the order, so it hangs there as a new leaf, and nothing else moves. min and max are walks too: as far left as the tree goes, or as far right.
the operations
tap a node to fill in its key.
insert 45 and watch the walk. remove 50: it has two children, so its successor moves up. or press next in order a few times and watch a stick grow.
- nodes looked at
- 0
- keys
- 7
- levels
- 3
search(t, key): node = t.root while node is not none: if key == node.key: return true node = node.left if key < node.key else node.right return false insert(t, key): parent, node = none, t.root while node is not none: if key == node.key: return false # already here parent = node node = node.left if key < node.key else node.right new = node(key) # where the walk fell off if parent is none: t.root = new elif key < parent.key: parent.left = new else: parent.right = new return true remove(t, key): parent, node = none, t.root while node is not none and node.key != key: parent = node node = node.left if key < node.key else node.right if node is none: return false if node.left and node.right: # two children parent, succ = node, node.right # the successor: right once, while succ.left: parent, succ = succ, succ.left # then left to the end node.key = succ.key # copy it up node = succ # and remove the successor instead child = node.left or node.right # at most one if parent is none: t.root = child elif parent.left is node: parent.left = child else: parent.right = child return truean interactive binary search tree that starts with 50 at the root, 30 and 70 under it, and 20, 40, 60 and 80 below. each key sits in the column of its rank, so the keys read in order from left to right. buttons insert, search for or remove a key you type, or tap a node to fill in its key; next in order inserts one more than the biggest key, and random builds a random tree of seven keys. a walk tints each link it takes, cyan going left and amber going right, with a white outline on the node it's at; a new key shows dashed where the walk fell off before it's linked in, and a successor moving up is white. the matching pseudocode line is highlighted, with counts of the nodes looked at, the keys and the levels. the figure holds 12 keys in 6 levels.
insert 45 and count the nodes the walk looks at. remove 50: it has two children, so its successor, 60, moves up. then press next in order a few times and watch the tree lean.
try it
insert 45. tap the node it hangs from.
tap a node.
a practice exercise on a binary search tree. some questions insert a key and ask which node it hangs from, answered by tapping the node. others remove a key with two children and ask which key takes its place, or search for a key and ask how many nodes the walk looks at.
pseudocode
search(t, key):
node = t.root
while node is not none:
if key == node.key: return true
node = node.left if key < node.key else node.right
return false
insert(t, key):
parent, node = none, t.root
while node is not none:
if key == node.key: return false # already here
parent = node
node = node.left if key < node.key else node.right
new = node(key) # where the walk fell off
if parent is none: t.root = new
elif key < parent.key: parent.left = new
else: parent.right = new
return true
remove(t, key):
parent, node = none, t.root
while node is not none and node.key != key:
parent = node
node = node.left if key < node.key else node.right
if node is none: return false
if node.left and node.right: # two children
parent, succ = node, node.right # the successor: right once,
while succ.left: parent, succ = succ, succ.left # then left to the end
node.key = succ.key # copy it up
node = succ # and remove the successor instead
child = node.left or node.right # at most one
if parent is none: t.root = child
elif parent.left is node: parent.left = child
else: parent.right = child
return trueevery walk is a loop, here and in every tab. a recursive version is shorter, but a tree can be as deep as it is big, as the next sections show, and python stops at 1000 levels of recursion.1
remove, up close
a leaf
remove 20
nothing hangs below 20, so it just goes
one child
remove 30
30's one child, 40, moves up into its place
two children
remove 50
50's successor, 60, the smallest key to its right, moves up
three small trees, each shown before and after a remove. a leaf, 20, just goes. a node with one child, 30, is replaced by that child, 40. a node with two children, the root 50, is replaced by its successor, 60, the smallest key to its right.
- a leaf just goes. its parent’s link becomes empty
- one child moves up. the child takes the node’s place. everything under it was already on the correct side of the node’s parent, so the order holds
- two children: the successor moves up. the successor is the next key up: go right once, then left as far as you can. it’s bigger than everything on the left and smaller than everything else on the right, so it fits the removed node’s place. it has no left child, so taking it out of its old spot is one of the easy cases. every tab copies the successor’s key up, then removes its old node
- the predecessor works too. the biggest key on the left fits just as well. always taking the successor is an arbitrary choice, and it adds up: in sedgewick and wayne’s demo, a tree of 150 keys leans left after many random removes and inserts2
the catch: sorted inserts
insert keys in sorted order and each new key is the biggest so far, so it hangs off the right of the one before. the tree turns into a stick, one node per level, and walking it is walking a linked list. 2000 sorted keys make 2000 levels, and every operation is O(n).
random orders do far better. 1000 keys in a random order made a tree 18 to 26 levels tall over 100 orders, 22 on average. a perfect tree of 1000 keys needs 10.
staying balanced
an avl tree is a binary search tree that checks itself after every change. each node’s two subtrees may differ by at most one level. when an insert or remove breaks that, a rotation fixes it on the way back up.
tap a node to fill in its key.
press next in order: the same sorted keys that make a plain tree a stick. at 3, this one rotates to stay balanced.
- nodes looked at
- 0
- keys
- 2
- levels
- 2
- rotations
- 0
insert(t, key): bst_insert(t, key) # the same walk and link as a plain bst for node on the path, back up to the root: rebalance(node) remove(t, key): bst_remove(t, key) for node on the path, back up to the root: rebalance(node) rebalance(node): # returns what takes its place b = levels(node.left) - levels(node.right) if b > 1: # the left side is 2 levels taller if balance(node.left) < 0: node.left = rotate_left(node.left) return rotate_right(node) if b < -1: # the right side is if balance(node.right) > 0: node.right = rotate_right(node.right) return rotate_left(node) return node rotate_right(node): # the left child comes up up = node.left node.left = up.right up.right = node return up rotate_left(node): # the right child comes up up = node.right node.right = up.left up.left = node return upthe same playground as an avl tree, starting with 1 and 2. each node shows its balance underneath: the levels of its left subtree minus the levels of its right. after an insert or remove, the walk goes back up the path, and a node whose balance reaches 2 or -2 rotates: the child on its taller side comes up and the node goes down beside it, while every key keeps its column. a count of rotations sits with the other counters. inserting 1 to 7 in order takes 4 rotations and ends 3 levels tall.
it starts with 1 and 2. press next in order: at 3, the root’s right side is 2 levels taller, and 2 rotates up to the top. by 7 there have been 4 rotations, and the tree is 3 levels tall, as short as 7 keys can be.
- a rotation keeps the order. rotate right: the left child comes up, the node goes down to its right, and the child’s right subtree moves across to the node’s left. every key stays in its column, so the in-order walk doesn’t change. only the levels do
- one rotation, or two. if the taller side leans the same way as its child, one rotation fixes it. if it zigzags, left then right, a first rotation straightens it and a second one fixes it
- how tall it can get. the sparsest avl trees hold 1, 2, 4, 7, 12, 20 and 33 keys for 1 to 7 levels: each is a root over the sparsest trees one and two levels shorter. so 1000 keys never take more than 14 levels, against 10 for a perfect tree. in practice it’s close to perfect: 2000 sorted keys make 11 levels, and 1000 random ones 12
insert(t, key):
bst_insert(t, key) # the same walk and link as a plain bst
for node on the path, back up to the root:
rebalance(node)
remove(t, key):
bst_remove(t, key)
for node on the path, back up to the root:
rebalance(node)
rebalance(node): # returns what takes its place
b = levels(node.left) - levels(node.right)
if b > 1: # the left side is 2 levels taller
if balance(node.left) < 0: node.left = rotate_left(node.left)
return rotate_right(node)
if b < -1: # the right side is
if balance(node.right) > 0: node.right = rotate_right(node.right)
return rotate_left(node)
return node
rotate_right(node): # the left child comes up
up = node.left
node.left = up.right
up.right = node
return up
rotate_left(node): # the right child comes up
up = node.right
node.right = up.left
up.left = node
return upthe tested typescript behind the figure:
/**
* AVL tree of numbers: a binary search tree that keeps each node's two subtrees within one level of each other.
* An insert or remove that breaks that rotates the tree back, so its height stays O(log n) and search, insert
* and remove stay O(log n), even when the keys arrive sorted. The height bound keeps recursion shallow.
*/
type Node = { key: number; left: Node | null; right: Node | null; levels: number };
const levels = (n: Node | null) => (n ? n.levels : 0);
const balance = (n: Node) => levels(n.left) - levels(n.right);
const fix = (n: Node) => {
n.levels = 1 + Math.max(levels(n.left), levels(n.right));
};
export class AVLTree {
#root: Node | null = null;
#size = 0;
#rotations = 0;
get size(): number {
return this.#size;
}
/** Rotations so far: a double rotation counts as two. */
get rotations(): number {
return this.#rotations;
}
contains(key: number): boolean {
let node = this.#root;
while (node) {
if (key === node.key) return true;
node = key < node.key ? node.left : node.right;
}
return false;
}
/** False if key is already here. */
insert(key: number): boolean {
const before = this.#size;
this.#root = this.#insert(this.#root, key);
return this.#size > before;
}
/** False if key isn't here. */
remove(key: number): boolean {
const before = this.#size;
this.#root = this.#remove(this.#root, key);
return this.#size < before;
}
/** How many levels: 0 for an empty tree. */
height(): number {
return levels(this.#root);
}
values(): number[] {
const out: number[] = [];
const walk = (n: Node | null) => {
if (!n) return;
walk(n.left);
out.push(n.key);
walk(n.right);
};
walk(this.#root);
return out;
}
/** A node, then its left subtree, then its right. Inserting these into a plain bst rebuilds the same shape. */
preorder(): number[] {
const out: number[] = [];
const walk = (n: Node | null) => {
if (!n) return;
out.push(n.key);
walk(n.left);
walk(n.right);
};
walk(this.#root);
return out;
}
#insert(node: Node | null, key: number): Node {
if (!node) {
this.#size += 1;
return { key, left: null, right: null, levels: 1 };
}
if (key < node.key) node.left = this.#insert(node.left, key);
else if (key > node.key) node.right = this.#insert(node.right, key);
else return node;
return this.#rebalance(node);
}
#remove(node: Node | null, key: number): Node | null {
if (!node) return null;
if (key < node.key) node.left = this.#remove(node.left, key);
else if (key > node.key) node.right = this.#remove(node.right, key);
else if (!node.left || !node.right) {
this.#size -= 1;
return node.left ?? node.right;
} else {
// two children: copy in the successor, then remove it from the right subtree
let next = node.right;
while (next.left) next = next.left;
node.key = next.key;
node.right = this.#remove(node.right, next.key);
}
return this.#rebalance(node);
}
// the subtrees differ by 2: a single rotation if the heavy child leans the same way, a double one if not
#rebalance(node: Node): Node {
fix(node);
const b = balance(node);
if (b > 1) {
if (balance(node.left!) < 0) node.left = this.#rotateLeft(node.left!);
return this.#rotateRight(node);
}
if (b < -1) {
if (balance(node.right!) > 0) node.right = this.#rotateRight(node.right!);
return this.#rotateLeft(node);
}
return node;
}
// the left child comes up, and the node becomes its right child. the keys' order doesn't change
#rotateRight(node: Node): Node {
const up = node.left!;
node.left = up.right;
up.right = node;
fix(node);
fix(up);
this.#rotations += 1;
return up;
}
#rotateLeft(node: Node): Node {
const up = node.right!;
node.right = up.left;
up.left = node;
fix(node);
fix(up);
this.#rotations += 1;
return up;
}
}complexity
| operation | random | sorted | avl |
|---|---|---|---|
| search | O(log n) | O(n) | O(log n) |
| insert | O(log n) | O(n) | O(log n) |
| remove | O(log n) | O(n) | O(log n) |
| min, max | O(log n) | O(n) | O(log n) |
| in order | O(n) | O(n) | O(n) |
a walk costs one step per level, so every operation but the full walk is O(h), the height. keys in a random order keep h near log n on average. sorted ones make h equal to n. an avl tree keeps h O(log n) whatever the order, for a little bookkeeping on every change.
- random order
- 20–27 levels, 22.9 on average
- sorted
- 1024 levels
- avl tree
- 12.0 levels
- at best
- 11 levels
a line chart of how many levels a tree has against how many keys it holds, from 1 to 1024 on a doubling scale. keys inserted in a random order, in cyan, stay low: a shaded band shows the lowest and highest over 20 orders, 20 to 27 levels at 1024 keys. sorted keys, in amber, make n levels and leave the chart at 30. an avl tree, dashed cyan, sits just above the dotted line for a perfect tree, 12 levels at 1024 against 11. a slider picks a size and reads off all four.
implementations
each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded inserts, removes and lookups checked against the language’s own set: python’s set, go’s map, rust’s BTreeSet, swift’s Set, a Set in typescript and an array of flags in c. they’re unbalanced, like the first playground, and every walk is a loop. c, rust and swift also free a million-node stick without recursion: by default, freeing a node first frees its children, one stack frame per level, and a stick that deep overflows the stack. an empty tree is where they differ: min gives go false, rust None, typescript undefined, c false, swift nil, and python raises ValueError.
// Package bst is a reference binary search tree, unbalanced: O(h) search, insert and remove, so O(log n)
// for keys in random order and O(n) for sorted ones. every walk is a loop, so a stick can't overflow the stack.
package bst
type node struct {
key int
left, right *node
}
// Tree is a binary search tree of distinct int keys: smaller keys go left, bigger keys go right.
// The zero value is an empty tree, ready to use.
type Tree struct {
root *node
size int
}
// Len returns how many keys are in the tree.
func (t *Tree) Len() int {
return t.size
}
// link returns the pointer that points at key's node, or at the nil where key would go:
// &t.root at the top, else a left or right field. insert and remove rewrite that one pointer,
// so the root needs no special case.
func (t *Tree) link(key int) **node {
link := &t.root
for *link != nil && (*link).key != key {
if key < (*link).key {
link = &(*link).left
} else {
link = &(*link).right
}
}
return link
}
// Contains reports whether key is in the tree.
func (t *Tree) Contains(key int) bool {
return *t.link(key) != nil
}
// Insert hangs key where the search for it falls off the tree. It returns false if key is already here.
func (t *Tree) Insert(key int) bool {
link := t.link(key)
if *link != nil {
return false
}
*link = &node{key: key}
t.size++
return true
}
// Remove takes key out. It returns false if key isn't here.
func (t *Tree) Remove(key int) bool {
link := t.link(key)
n := *link
if n == nil {
return false
}
if n.left != nil && n.right != nil {
// two children: copy in the successor, the smallest key on the right, and remove its node instead
link = &n.right
for (*link).left != nil {
link = &(*link).left
}
n.key = (*link).key
n = *link
}
// at most one child now, and it takes the node's place
if n.left != nil {
*link = n.left
} else {
*link = n.right
}
t.size--
return true
}
// Min returns the smallest key, as far left as the tree goes, or false if the tree is empty.
func (t *Tree) Min() (int, bool) {
if t.root == nil {
return 0, false
}
n := t.root
for n.left != nil {
n = n.left
}
return n.key, true
}
// Max returns the biggest key, as far right as the tree goes, or false if the tree is empty.
func (t *Tree) Max() (int, bool) {
if t.root == nil {
return 0, false
}
n := t.root
for n.right != nil {
n = n.right
}
return n.key, true
}
// Height returns how many levels the tree has: 0 when empty, 1 for one node, n for a stick of n.
func (t *Tree) Height() int {
var row []*node
if t.root != nil {
row = append(row, t.root)
}
levels := 0
// one row at a time, so even a stick takes no recursion
for len(row) > 0 {
var next []*node
for _, n := range row {
if n.left != nil {
next = append(next, n.left)
}
if n.right != nil {
next = append(next, n.right)
}
}
row = next
levels++
}
return levels
}
// Values returns the keys in order, smallest first: go left as far as you can, take the last node
// you passed, then step right and repeat.
func (t *Tree) Values() []int {
out := make([]int, 0, t.size)
var stack []*node // the nodes passed on the way left, not taken yet
n := t.root
for n != nil || len(stack) > 0 {
for ; n != nil; n = n.left {
stack = append(stack, n)
}
n = stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, n.key)
n = n.right
}
return out
}
// Preorder returns the keys in preorder: a node, then its left subtree, then its right.
// Inserting them in this order rebuilds the same tree.
func (t *Tree) Preorder() []int {
out := make([]int, 0, t.size)
var stack []*node
if t.root != nil {
stack = append(stack, t.root)
}
for len(stack) > 0 {
n := stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, n.key)
// right goes on first, so left comes off first
if n.right != nil {
stack = append(stack, n.right)
}
if n.left != nil {
stack = append(stack, n.left)
}
}
return out
}//! binary search tree, unbalanced: O(h) search, insert and remove, so O(log n) for keys in random order and O(n) for sorted ones. every walk is a loop, so a stick can't overflow the stack.
use std::cmp::Ordering;
type Link = Option<Box<Node>>;
struct Node {
key: i64,
left: Link,
right: Link,
}
/// A set of integer keys. At every node, smaller keys are in the left subtree and bigger keys in
/// the right. Nothing rebalances it, so keys inserted in sorted order make a stick, one node per
/// level.
pub struct Bst {
root: Link,
len: usize,
}
impl Bst {
/// Makes an empty tree.
pub fn new() -> Self {
Self { root: None, len: 0 }
}
/// The number of keys.
pub fn len(&self) -> usize {
self.len
}
/// Whether there are no keys.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Whether `key` is here. Each step goes left for a smaller key, right for a bigger one.
pub fn contains(&self, key: i64) -> bool {
let mut node = self.root.as_deref();
while let Some(n) = node {
node = match key.cmp(&n.key) {
Ordering::Less => n.left.as_deref(),
Ordering::Greater => n.right.as_deref(),
Ordering::Equal => return true,
};
}
false
}
/// The link that points at `key`'s node, or the empty one where `key` would hang: the root or
/// a node's `left` or `right`. Insert and remove rewrite that one `Option`, so the root needs
/// no special case.
fn link(&mut self, key: i64) -> &mut Link {
let mut link = &mut self.root;
// look with as_ref, then step with as_mut: a mutable borrow taken just to look would keep
// the link borrowed after the loop
while link.as_ref().is_some_and(|node| node.key != key) {
let node = link.as_mut().expect("the loop checked it");
link = if key < node.key {
&mut node.left
} else {
&mut node.right
};
}
link
}
/// Hangs `key` where the search for it falls off the tree. False if it's already here.
pub fn insert(&mut self, key: i64) -> bool {
let link = self.link(key);
if link.is_some() {
return false;
}
*link = Some(Box::new(Node {
key,
left: None,
right: None,
}));
self.len += 1;
true
}
/// Takes `key` out. False if it isn't here.
pub fn remove(&mut self, key: i64) -> bool {
let link = self.link(key);
let Some(node) = link else {
return false;
};
// two children: copy in the successor, the smallest key on the right, and remove its node
// instead. from here on, link points at the node that goes
let link = if node.left.is_some() && node.right.is_some() {
let mut next = &mut node.right;
while next.as_ref().is_some_and(|n| n.left.is_some()) {
next = &mut next.as_mut().expect("the loop checked it").left;
}
node.key = next.as_ref().expect("the right subtree isn't empty").key;
next
} else {
link
};
// at most one child now, and it takes the node's place
*link = link.take().and_then(|gone| gone.left.or(gone.right));
self.len -= 1;
true
}
/// The smallest key, as far left as the tree goes, or `None` if it's empty.
pub fn min(&self) -> Option<i64> {
let mut node = self.root.as_deref()?;
while let Some(left) = node.left.as_deref() {
node = left;
}
Some(node.key)
}
/// The biggest key, as far right as the tree goes, or `None` if it's empty.
pub fn max(&self) -> Option<i64> {
let mut node = self.root.as_deref()?;
while let Some(right) = node.right.as_deref() {
node = right;
}
Some(node.key)
}
/// How many levels: 0 for an empty tree, 1 for one node, n for a stick of n.
pub fn height(&self) -> usize {
let mut levels = 0;
// one row at a time, so even a stick takes no recursion
let mut row: Vec<&Node> = self.root.as_deref().into_iter().collect();
while !row.is_empty() {
levels += 1;
row = row
.into_iter()
.flat_map(|n| [n.left.as_deref(), n.right.as_deref()])
.flatten()
.collect();
}
levels
}
/// The keys in order, smallest first: walk left as far as you can, then take a node and step
/// right.
pub fn values(&self) -> Vec<i64> {
let mut out = Vec::with_capacity(self.len);
let mut stack = Vec::new(); // the nodes passed on the way down, to come back to
let mut node = self.root.as_deref();
loop {
while let Some(n) = node {
stack.push(n);
node = n.left.as_deref();
}
let Some(next) = stack.pop() else { break };
out.push(next.key);
node = next.right.as_deref();
}
out
}
/// The keys in preorder: a node, then its left subtree, then its right. Inserting them in
/// this order rebuilds the tree.
pub fn preorder(&self) -> Vec<i64> {
let mut out = Vec::with_capacity(self.len);
let mut stack: Vec<&Node> = self.root.as_deref().into_iter().collect();
while let Some(node) = stack.pop() {
out.push(node.key);
// right first, so the left comes off the stack first. extend skips a None
stack.extend(node.right.as_deref());
stack.extend(node.left.as_deref());
}
out
}
}
impl Default for Bst {
fn default() -> Self {
Self::new()
}
}
/// The default drop would free the root, whose drop frees its children, and so on: one stack
/// frame per level, so a deep stick overflows the stack. This loop frees every node with no
/// recursion and no extra memory, by rotating left children up until the node it holds has none.
impl Drop for Bst {
fn drop(&mut self) {
let mut cur = self.root.take();
while let Some(mut node) = cur {
if let Some(mut left) = node.left.take() {
// rotate right: the left child comes up, and the node becomes its right child
node.left = left.right.take();
left.right = Some(node);
cur = Some(left);
} else {
// no left child: go on from the right one. the node has no children now, so it
// drops on its own
cur = node.right.take();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
fn from(keys: impl IntoIterator<Item = i64>) -> Bst {
let mut t = Bst::new();
for key in keys {
t.insert(key);
}
t
}
/// A stick of keys 0 to n - 1, built straight through the fields: each new node goes on top,
/// with the old root as its one child. Inserting them would walk the whole stick every time,
/// O(n^2) steps in all.
fn stick(n: i64, left: bool) -> Bst {
let mut t = Bst::new();
for i in 0..n {
// a left stick has the biggest key on top, a right stick the smallest
let key = if left { i } else { n - 1 - i };
let mut node = Box::new(Node {
key,
left: None,
right: None,
});
if left {
node.left = t.root.take();
} else {
node.right = t.root.take();
}
t.root = Some(node);
t.len += 1;
}
t
}
// 50 at the root, 30 and 70 under it, then 20, 40, 60 and 80: three full levels
const FULL: [i64; 7] = [50, 30, 70, 20, 40, 60, 80];
#[test]
fn starts_empty() {
let mut t = Bst::new();
assert!(t.is_empty());
assert_eq!(
(t.len(), t.height(), t.contains(5), t.remove(5)),
(0, 0, false, false)
);
assert_eq!((t.min(), t.max()), (None, None));
assert!(t.values().is_empty() && t.preorder().is_empty());
}
#[test]
fn insert_sends_smaller_keys_left_and_bigger_keys_right() {
let t = from(FULL);
assert_eq!(t.preorder(), [50, 30, 20, 40, 70, 60, 80]);
assert_eq!(t.values(), [20, 30, 40, 50, 60, 70, 80]);
assert_eq!((t.len(), t.height()), (7, 3));
}
#[test]
fn inserting_a_key_thats_already_there_changes_nothing() {
let mut t = from(FULL);
assert!(!t.insert(40));
assert_eq!(t.len(), 7);
assert_eq!(t.preorder(), [50, 30, 20, 40, 70, 60, 80]);
}
#[test]
fn contains_finds_the_keys_that_went_in_and_nothing_else() {
let t = from(FULL);
assert!(FULL.into_iter().all(|k| t.contains(k)));
assert!([10, 35, 55, 90].into_iter().all(|k| !t.contains(k)));
}
#[test]
fn min_is_the_leftmost_key_max_the_rightmost() {
let t = from(FULL);
assert_eq!((t.min(), t.max()), (Some(20), Some(80)));
}
#[test]
fn remove_a_leaf_it_just_goes() {
let mut t = from(FULL);
assert!(t.remove(20));
assert_eq!(t.preorder(), [50, 30, 40, 70, 60, 80]);
}
#[test]
fn remove_a_node_with_one_child_the_child_takes_its_place() {
let mut t = from(FULL);
t.remove(20);
assert!(t.remove(30));
assert_eq!(t.preorder(), [50, 40, 70, 60, 80]);
}
#[test]
fn remove_a_node_with_two_children_its_successor_takes_its_place() {
let mut t = from(FULL);
assert!(t.remove(50));
assert_eq!(t.preorder(), [60, 30, 20, 40, 70, 80]);
}
#[test]
fn the_successors_right_child_moves_up_into_its_place() {
let mut t = from([50, 30, 70, 60, 65, 80]);
t.remove(50);
assert_eq!(t.preorder(), [60, 30, 70, 65, 80]);
}
#[test]
fn the_successor_can_be_the_right_child_itself() {
let mut t = from([50, 30, 70, 60, 80]);
t.remove(70);
assert_eq!(t.preorder(), [50, 30, 80, 60]);
}
#[test]
fn remove_at_the_root_the_last_key_and_a_missing_key() {
let mut t = from([10, 20]);
t.remove(10);
assert_eq!(t.preorder(), [20]);
let mut one = from([7]);
assert_eq!(
(one.remove(7), one.len(), one.preorder()),
(true, 0, vec![])
);
assert!(!from(FULL).remove(55));
}
#[test]
fn inserting_a_trees_preorder_rebuilds_the_same_tree() {
let t = from([41, 20, 65, 11, 29, 50, 91, 32, 72, 99]);
assert_eq!(from(t.preorder()).preorder(), t.preorder());
}
#[test]
fn sorted_inserts_make_a_stick_as_tall_as_the_tree_is_big() {
let mut t = from(0..2000);
assert_eq!((t.len(), t.height()), (2000, 2000));
// every walk is a loop, so the deepest key is no trouble
assert_eq!(
(t.contains(1999), t.remove(1999), t.max(), t.values().len()),
(true, true, Some(1998), 1999)
);
}
#[test]
fn a_million_node_stick_drops_without_overflowing_the_stack() {
for left in [false, true] {
let t = stick(1_000_000, left);
assert_eq!((t.len(), t.height()), (1_000_000, 1_000_000));
drop(t);
}
}
#[test]
fn agrees_with_btreeset_over_2000_seeded_ops() {
// xorshift32 seeded with 42, like the other tests here
let mut state: u32 = 42;
let mut next = || {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
i64::from(state)
};
let mut t = Bst::new();
let mut model = BTreeSet::new();
for _ in 0..2000 {
let key = next() % 100;
match next() % 5 {
0 => assert_eq!(t.insert(key), model.insert(key)),
1 => assert_eq!(t.remove(key), model.remove(&key)),
2 => assert_eq!(t.contains(key), model.contains(&key)),
3 => assert_eq!(t.min(), model.first().copied()),
_ => assert_eq!(t.max(), model.last().copied()),
}
assert_eq!(t.len(), model.len());
assert!(t.height() <= t.len());
assert_eq!(t.values(), model.iter().copied().collect::<Vec<_>>());
}
}
}/**
* Binary search tree, unbalanced: O(h) search, insert and remove, so O(log n) for keys in random order and O(n)
* for sorted ones. Every walk is a loop, so a stick can't overflow the stack.
*/
type Node = { key: number; left: Node | null; right: Node | null };
export class BST {
#root: Node | null = null;
#size = 0;
get size(): number {
return this.#size;
}
contains(key: number): boolean {
let node = this.#root;
while (node) {
if (key === node.key) return true;
node = key < node.key ? node.left : node.right;
}
return false;
}
/** Hang key where the search for it falls off the tree. False if it's already here. */
insert(key: number): boolean {
let parent: Node | null = null;
let node = this.#root;
while (node) {
if (key === node.key) return false;
parent = node;
node = key < node.key ? node.left : node.right;
}
const fresh: Node = { key, left: null, right: null };
if (!parent) this.#root = fresh;
else if (key < parent.key) parent.left = fresh;
else parent.right = fresh;
this.#size += 1;
return true;
}
/** Take key out. False if it isn't here. */
remove(key: number): boolean {
let parent: Node | null = null;
let node = this.#root;
while (node && node.key !== key) {
parent = node;
node = key < node.key ? node.left : node.right;
}
if (!node) return false;
if (node.left && node.right) {
// two children: copy in the successor, the smallest key on the right, and remove its node instead
let next: Node = node.right;
parent = node;
while (next.left) {
parent = next;
next = next.left;
}
node.key = next.key;
node = next;
}
// at most one child now, and it takes the node's place
const child = node.left ?? node.right;
if (!parent) this.#root = child;
else if (parent.left === node) parent.left = child;
else parent.right = child;
this.#size -= 1;
return true;
}
/** The smallest key: as far left as the tree goes. */
min(): number | undefined {
let node = this.#root;
while (node?.left) node = node.left;
return node?.key;
}
/** The biggest key: as far right as the tree goes. */
max(): number | undefined {
let node = this.#root;
while (node?.right) node = node.right;
return node?.key;
}
/** How many levels: 0 for an empty tree, 1 for one node, n for a stick of n. */
height(): number {
let levels = 0;
// one row at a time, so even a stick takes no recursion
for (let row = this.#root ? [this.#root] : []; row.length; levels++) {
row = row.flatMap((n) => [n.left, n.right].filter((c): c is Node => c !== null));
}
return levels;
}
/** The keys in order, smallest first: walk left as far as you can, then take a node and step right. */
values(): number[] {
const out: number[] = [];
const stack: Node[] = [];
let node = this.#root;
while (node || stack.length) {
for (; node; node = node.left) stack.push(node);
const next = stack.pop()!;
out.push(next.key);
node = next.right;
}
return out;
}
/** The keys in preorder: a node, then its left subtree, then its right. Inserting them in this order rebuilds the tree. */
preorder(): number[] {
const out: number[] = [];
const stack = this.#root ? [this.#root] : [];
while (stack.length) {
const node = stack.pop()!;
out.push(node.key);
if (node.right) stack.push(node.right);
if (node.left) stack.push(node.left);
}
return out;
}
}/* binary search tree, unbalanced: O(h) search, insert and remove, so O(log n) for keys in random order and O(n) for sorted ones. every walk is a loop, so a stick can't overflow the stack. */
#include "bst.h"
#include <stdlib.h>
void bst_init(Bst *t) {
t->root = NULL;
t->len = 0;
}
/* one loop, no recursion and no stack. a node with a left child is rotated right: the left child
comes up, and the node becomes its right child. a node with no left child is freed, and its right
child is next. each rotation adds a node to the chain of right links the loop frees down, so there
are at most n rotations */
void bst_free(Bst *t) {
BstNode *n = t->root;
while (n) {
if (n->left) {
BstNode *up = n->left;
n->left = up->right;
up->right = n;
n = up;
} else {
BstNode *next = n->right;
free(n);
n = next;
}
}
bst_init(t);
}
bool bst_contains(const Bst *t, int key) {
const BstNode *n = t->root;
while (n) {
if (key == n->key) return true;
n = key < n->key ? n->left : n->right;
}
return false;
}
/* the link that points at key's node: &root, or the left or right field of its parent. if key isn't
here, it's the NULL link where key would hang. inserting and removing rewrite that one pointer, so
the root needs no special case */
static BstNode **link_to(Bst *t, int key) {
BstNode **link = &t->root;
while (*link && (*link)->key != key) {
BstNode *n = *link;
link = key < n->key ? &n->left : &n->right;
}
return link;
}
bool bst_insert(Bst *t, int key, bool *added) {
BstNode **link = link_to(t, key);
*added = false;
if (*link) return true; /* already here: nothing changes */
BstNode *n = malloc(sizeof *n);
if (!n) return false;
n->key = key;
n->left = n->right = NULL;
*link = n;
t->len++;
*added = true;
return true;
}
bool bst_remove(Bst *t, int key) {
BstNode **link = link_to(t, key);
BstNode *gone = *link;
if (!gone) return false;
if (gone->left && gone->right) {
/* two children: copy in the successor, the smallest key on the right, and remove its node
instead. it has no left child (that would be smaller still), so it's an easy case */
link = &gone->right;
while ((*link)->left) link = &(*link)->left;
gone->key = (*link)->key;
gone = *link;
}
/* at most one child now, and it takes the node's place */
*link = gone->left ? gone->left : gone->right;
free(gone);
t->len--;
return true;
}
/* the smallest key: as far left as the tree goes */
bool bst_min(const Bst *t, int *out) {
const BstNode *n = t->root;
if (!n) return false;
while (n->left) n = n->left;
*out = n->key;
return true;
}
/* the biggest key: as far right as the tree goes */
bool bst_max(const Bst *t, int *out) {
const BstNode *n = t->root;
if (!n) return false;
while (n->right) n = n->right;
*out = n->key;
return true;
}
/* one row at a time, so even a stick takes no recursion. every node goes through the queue once, so
len slots are enough. an empty tree stops before the malloc: malloc(0) can return NULL, which would
look like a failure */
bool bst_height(const Bst *t, size_t *out) {
if (t->len == 0) {
*out = 0;
return true;
}
const BstNode **queue = malloc(t->len * sizeof *queue);
if (!queue) return false;
size_t head = 0, tail = 0, levels = 0;
queue[tail++] = t->root;
for (; head < tail; levels++) {
/* head to tail is one whole row: take it, queueing the row below behind it */
for (size_t end = tail; head < end; head++) {
const BstNode *n = queue[head];
if (n->left) queue[tail++] = n->left;
if (n->right) queue[tail++] = n->right;
}
}
free(queue);
*out = levels;
return true;
}
/* in order, smallest first: walk left as far as you can, stacking the path, then take a node and step
right. a stick leaning left stacks every node at once, so the stack gets len slots */
bool bst_values(const Bst *t, int *out) {
if (t->len == 0) return true; /* nothing to write */
const BstNode **stack = malloc(t->len * sizeof *stack);
if (!stack) return false;
size_t top = 0;
const BstNode *n = t->root;
while (n || top > 0) {
for (; n; n = n->left) stack[top++] = n;
n = stack[--top];
*out++ = n->key;
n = n->right;
}
free(stack);
return true;
}
/* a node, then its left subtree, then its right. the right child goes on the stack first, so the left
one comes off first. every node goes on once, so len slots are enough */
bool bst_preorder(const Bst *t, int *out) {
if (t->len == 0) return true;
const BstNode **stack = malloc(t->len * sizeof *stack);
if (!stack) return false;
size_t top = 0;
stack[top++] = t->root;
while (top > 0) {
const BstNode *n = stack[--top];
*out++ = n->key;
if (n->right) stack[top++] = n->right;
if (n->left) stack[top++] = n->left;
}
free(stack);
return true;
}/// binary search tree, unbalanced: O(h) search, insert and remove, so O(log n) for keys in random order and O(n) for sorted ones. every walk is a loop, so a stick can't overflow the stack.
/// a class, since its nodes are shared references: copying a struct around them wouldn't copy the tree. it also needs a deinit, to free a deep tree in a loop.
public final class BST {
final class Node {
var key: Int
var left: Node?
var right: Node?
init(_ key: Int) {
self.key = key
}
}
// internal, not private: the tests build a million-node stick through it directly, since a million inserts
// into a stick would take O(n^2)
var root: Node?
public private(set) var count = 0
public init() {}
public func contains(_ key: Int) -> Bool {
var cur = root
while let node = cur {
if key == node.key { return true }
cur = key < node.key ? node.left : node.right
}
return false
}
/// hangs key where the search for it falls off the tree. false if it's already here
@discardableResult
public func insert(_ key: Int) -> Bool {
var parent: Node? = nil
var cur = root
while let node = cur {
if key == node.key { return false }
parent = node
cur = key < node.key ? node.left : node.right
}
let fresh = Node(key)
if let parent {
if key < parent.key { parent.left = fresh } else { parent.right = fresh }
} else {
root = fresh
}
count += 1
return true
}
/// takes key out. false if it isn't here
@discardableResult
public func remove(_ key: Int) -> Bool {
var parent: Node? = nil
var cur = root
while let node = cur, node.key != key {
parent = node
cur = key < node.key ? node.left : node.right
}
guard var node = cur else { return false }
if node.left != nil, var next = node.right {
// two children: copy in the successor, the smallest key on the right, and remove its node instead
parent = node
while let left = next.left {
parent = next
next = left
}
node.key = next.key
node = next
}
// at most one child now, and it takes the node's place
let child = node.left ?? node.right
if let parent {
if parent.left === node { parent.left = child } else { parent.right = child }
} else {
root = child
}
count -= 1
return true
}
/// the smallest key: as far left as the tree goes
public func min() -> Int? {
guard var node = root else { return nil }
while let left = node.left { node = left }
return node.key
}
/// the biggest key: as far right as the tree goes
public func max() -> Int? {
guard var node = root else { return nil }
while let right = node.right { node = right }
return node.key
}
/// how many levels: 0 for an empty tree, 1 for one node, n for a stick of n
public var height: Int {
var levels = 0
// one row at a time, so even a stick takes no recursion
var row: [Node] = root.map { [$0] } ?? []
while !row.isEmpty {
levels += 1
row = row.flatMap { [$0.left, $0.right].compactMap { $0 } }
}
return levels
}
/// the keys in order, smallest first: walk left as far as you can, then take a node and step right
public var values: [Int] {
var out: [Int] = []
var stack: [Node] = []
var cur = root
while cur != nil || !stack.isEmpty {
while let node = cur {
stack.append(node)
cur = node.left
}
let next = stack.removeLast()
out.append(next.key)
cur = next.right
}
return out
}
/// the keys in preorder: a node, then its left subtree, then its right. inserting them in this order rebuilds the tree
public var preorder: [Int] {
var out: [Int] = []
var stack: [Node] = root.map { [$0] } ?? []
while let node = stack.popLast() {
out.append(node.key)
// the right goes on first, so the left comes off first
if let right = node.right { stack.append(right) }
if let left = node.left { stack.append(left) }
}
return out
}
// releasing the root would release its children from inside that release, and theirs from inside those: one
// stack frame per level, enough to crash on a deep stick. take the tree apart in a loop instead, with no stack.
// while a node has a left child, rotate right to bring that child up. once it has none, step to its right
// child and cut the link, so the node is freed with no children to release
deinit {
var cur = root
root = nil
while let node = cur {
if let left = node.left {
// rotate right: left comes up, and node becomes its right child
node.left = left.right
left.right = node
cur = left
} else {
cur = node.right
node.right = nil
}
}
}
}"""binary search tree, unbalanced: O(h) search, insert and remove, so O(log n) for keys in random order and O(n) for sorted ones. every walk is a loop, so a stick can't overflow the stack."""
from __future__ import annotations
from typing import Iterator
class _Node:
__slots__ = ("key", "left", "right")
def __init__(self, key: int) -> None:
self.key = key
self.left: _Node | None = None
self.right: _Node | None = None
class BST:
"""Int keys, no repeats. Smaller keys live in a node's left subtree, bigger ones in its right."""
def __init__(self) -> None:
self._root: _Node | None = None
self._size = 0
def __len__(self) -> int:
return self._size
def __contains__(self, key: int) -> bool:
"""Walk one path down: left for a smaller key, right for a bigger one."""
node = self._root
while node is not None:
if key == node.key:
return True
node = node.left if key < node.key else node.right
return False
def __iter__(self) -> Iterator[int]:
"""Yield the keys in order, smallest first.
Walk left as far as you can, then take a node and step right.
"""
stack: list[_Node] = [] # the nodes passed on the way down, each one waiting its turn
node = self._root
while node is not None or stack:
while node is not None:
stack.append(node)
node = node.left
node = stack.pop()
yield node.key
node = node.right
def insert(self, key: int) -> bool:
"""Hang key where the search for it falls off the tree. Return False if it's already here."""
parent: _Node | None = None
node = self._root
while node is not None:
if key == node.key:
return False
parent = node
node = node.left if key < node.key else node.right
fresh = _Node(key)
if parent is None:
self._root = fresh
elif key < parent.key:
parent.left = fresh
else:
parent.right = fresh
self._size += 1
return True
def remove(self, key: int) -> bool:
"""Take key out. Return False if it isn't here."""
parent: _Node | None = None
node = self._root
while node is not None and node.key != key:
parent = node
node = node.left if key < node.key else node.right
if node is None:
return False
if node.left is not None and node.right is not None:
# two children: copy in the successor, the smallest key on the right,
# then remove the successor's node instead. it has no left child
parent = node
successor = node.right
while successor.left is not None:
parent = successor
successor = successor.left
node.key = successor.key
node = successor
# at most one child now, and it takes the node's place
child = node.left if node.left is not None else node.right
if parent is None:
self._root = child
elif parent.left is node:
parent.left = child
else:
parent.right = child
self._size -= 1
return True
def min(self) -> int:
"""Return the smallest key: as far left as the tree goes."""
node = self._root
if node is None:
raise ValueError("min of an empty tree") # what min([]) raises too
while node.left is not None:
node = node.left
return node.key
def max(self) -> int:
"""Return the biggest key: as far right as the tree goes."""
node = self._root
if node is None:
raise ValueError("max of an empty tree")
while node.right is not None:
node = node.right
return node.key
def height(self) -> int:
"""Count the levels: 0 for an empty tree, 1 for one node, n for a stick of n."""
levels = 0
row = [self._root] if self._root is not None else []
# one row at a time, so even a stick takes no recursion
while row:
row = [child for node in row for child in (node.left, node.right) if child is not None]
levels += 1
return levels
def preorder(self) -> list[int]:
"""Return the keys in preorder: a node, then its left subtree, then its right.
Inserting them in this order rebuilds the same tree.
"""
out: list[int] = []
stack = [self._root] if self._root is not None else []
while stack:
node = stack.pop()
out.append(node.key)
# the right child goes on first, so the left one comes off first
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return outpitfalls
- recursion on a stick. a recursive insert, walk or free takes one stack frame per level, and a stick of n keys has n levels. python stops at 10001
- sorted input. keys that arrive sorted, or nearly sorted, build a stick. shuffle them first, or use a balanced tree
- duplicates. decide what an equal key does. here insert ignores it, so the tree is a set. a multiset can keep a count in each node
- the wrong replacement. a node with two children has to be replaced by its successor or its predecessor. moving one of its children up instead breaks the order
- the root. inserting into an empty tree, or removing the root, changes the root itself. a pointer to the link handles every case in one path, as the go, c and rust tabs do
variants
- avl tree. balanced by level counts, as above
- red-black tree. each node is red or black, and rules on the colors keep the longest path at most twice the shortest. that’s looser than avl, so it rotates less: a remove rotates at most three times, where an avl remove can rotate at every level on the way up. java’s
TreeMapis one,3 and so is the tree behind glibc’stsearch4 - b-tree. each node holds many keys in a sorted array, so the tree is shallow and each node is one read. rust’s
BTreeMapis one, with B = 6, so up to 11 keys a node. its documentation explains why it isn’t a binary tree: each node is its own allocation, and each comparison may be a cache miss5 - treap. each node also gets a random priority, kept in heap order, so the tree takes the shape of one built from keys in a random order
- splay tree. each access rotates the key it found up to the root, so keys used often stay near the top
practice
- search in a binary search tree (opens in a new tab): the walk
- insert into a binary search tree (opens in a new tab): the walk, then a new leaf
- delete node in a bst (opens in a new tab): the three cases
- validate binary search tree (opens in a new tab): every key within the bounds its ancestors set
- kth smallest element in a bst (opens in a new tab): the in-order walk, stopped early
- convert sorted array to binary search tree (opens in a new tab): the middle key on top, for the shortest tree
how real libraries do it
- java.
TreeMapis a red-black tree, with log n time forcontainsKey,get,putandremove, adapted from cormen, leiserson and rivest3 - rust.
BTreeMapandBTreeSetare b-trees: fewer, fuller nodes, which suits the cpu cache better than one node per key5 - c. posix
tsearchkeeps a binary search tree,6 and glibc’s is red-black4
sources
-
pycore_ceval.h (opens in a new tab) in cpython 3.15.0:
Py_DEFAULT_RECURSION_LIMITis 1000. ↩ ↩2 -
binary search trees (opens in a new tab), section 3.2 of sedgewick and wayne’s algorithms, 4th edition: hibbard’s 1962 deletion replaces a node with its successor. the choice of the successor is arbitrary and not symmetric, and after repeated random deletes and inserts, a tree of 150 nodes becomes skewed to the left. ↩
-
TreeMap.java (opens in a new tab) at jdk-21-ga: a red-black tree based
NavigableMap, with guaranteed log(n) time forcontainsKey,get,putandremove, its algorithms adapted from cormen, leiserson and rivest’s introduction to algorithms. ↩ ↩2 -
tsearch.c (opens in a new tab) in glibc 2.42: “tree search for red/black trees”. ↩ ↩2
-
BTreeMap (opens in a new tab) in the rust docs: a b-tree, since in a binary search tree every element is its own heap allocation and every comparison is a potential cache miss. node.rs (opens in a new tab) at rust 1.99.1 sets
Bto 6 and a node’s capacity to2 * B - 1, 11 keys. ↩ ↩2 -
tsearch (opens in a new tab) in posix, ieee std 1003.1-2024:
tdelete,tfind,tsearchandtwalkmanage a binary search tree. ↩