Data structure · Trees and heaps

Binary search tree

A binary tree ordered so that an inorder walk is sorted: search, insert and delete in O(h), which is O(log n) only while the tree stays balanced.

The derivations, edge cases and exercises are in the lesson Binary search trees: search, insert, delete and the cost of height. Open it full width in the playground.

On this page
  1. The idea
  2. Operations
  3. Invariants
  4. When to use it
  5. Built-in equivalents
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Every node’s key is greater than all keys in its left subtree and less than all keys in its right subtree. A search compares with the root and descends one side, so it costs one comparison per level.

The height h decides everything. Random insertions keep h near log n, but inserting sorted keys builds a path of height n. Balanced variants (red-black, AVL) rotate nodes to keep h = O(log n); the built-in sorted maps use them.

Representation. Linked nodes { key, left, right } from a root reference.

Operations

Binary search tree operations and their complexity
OperationTimeExtra spaceNotes
SearchO(h)O(1) iterative
InsertO(h)O(1) iterative
DeleteO(h)O(1) iterativeTwo children: replace with the inorder successor, then delete that.
Min / maxO(h)O(1)
Inorder traversalO(n)O(h)Yields the keys in sorted order.

Invariants

What stays true before and after every operation.

  • For every node: all keys in the left subtree < key < all keys in the right subtree (no duplicates here).
  • An inorder traversal visits the keys in increasing order.
  • h is between ⌊log₂ n⌋ and n − 1.

When to use it

Use it when

  • You need ordered keys with fast insert and delete: sorted maps, range queries, floor and ceiling lookups.
  • You want to learn the mechanics that balanced trees build on.

Avoid it when

  • Keys may arrive sorted and the tree does not rebalance: it degenerates to a linked list.
  • You only need membership or lookup by key; a hash table is simpler and faster on average.

Built-in equivalents

What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.

C#

SortedDictionary<TKey, TValue> and SortedSet<T> are balanced (red-black) trees.

Python

No balanced tree in the standard library; keep a sorted list with bisect or use a dict and sort when needed.

Java

TreeMap and TreeSet are red-black trees with floor, ceiling and range views.

C++

std::map and std::set are ordered associative containers, typically red-black trees.

Step through it

The interactive lab for binary search tree: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

The same tree in four languages, each checked against one shared fixture (all three delete cases, a deep successor, duplicates, missing keys, an empty tree, a degenerate chain, negative and extreme keys) with the invariant checked after every operation, and 300 random runs of 60 operations compared with a sorted-list model.

namespace Bekadan.Dsa.Examples.Trees;
 
/// <summary>
/// An unbalanced binary search tree of distinct int keys. Every key in a node's
/// left subtree is smaller and every key in its right subtree larger. Insert,
/// Contains, Remove, Min and Max cost O(h): O(log n) when the tree is balanced,
/// O(n) when it degenerates into a chain (e.g. keys inserted in sorted order).
/// SortedSet&lt;T&gt; keeps the same contract balanced (a red-black tree).
/// </summary>
public sealed class BinarySearchTree
{
    private sealed class Node(int key)
    {
        public int Key = key;
        public Node? Left;
        public Node? Right;
    }
 
    private Node? _root;
 
    public int Count { get; private set; }
 
    /// <summary>Adds the key; returns false if it is already present.</summary>
    public bool Insert(int key)
    {
        if (_root is null)
        {
            _root = new Node(key);
            Count++;
            return true;
        }
        var node = _root;
        while (true)
        {
            int cmp = key.CompareTo(node.Key);
            if (cmp == 0)
                return false;
            var child = cmp < 0 ? node.Left : node.Right;
            if (child is null)
            {
                if (cmp < 0)
                    node.Left = new Node(key);
                else
                    node.Right = new Node(key);
                Count++;
                return true;
            }
            node = child;
        }
    }
 
    public bool Contains(int key)
    {
        var node = _root;
        while (node is not null)
        {
            int cmp = key.CompareTo(node.Key);
            if (cmp == 0)
                return true;
            node = cmp < 0 ? node.Left : node.Right;
        }
        return false;
    }
 
    /// <summary>Removes the key; returns false if it was not present.</summary>
    public bool Remove(int key)
    {
        int before = Count;
        _root = Remove(_root, key);
        return Count < before;
    }
 
    /// <summary>Deletes key from the subtree and returns the subtree's new root.</summary>
    private Node? Remove(Node? node, int key)
    {
        if (node is null)
            return null;
        int cmp = key.CompareTo(node.Key);
        if (cmp < 0)
        {
            node.Left = Remove(node.Left, key);
            return node;
        }
        if (cmp > 0)
        {
            node.Right = Remove(node.Right, key);
            return node;
        }
        if (node.Left is null)
        {
            Count--;
            return node.Right; // a leaf returns null; otherwise the right child moves up
        }
        if (node.Right is null)
        {
            Count--;
            return node.Left;
        }
        var successor = node.Right;
        while (successor.Left is not null)
            successor = successor.Left;
        node.Key = successor.Key;
        node.Right = Remove(node.Right, successor.Key);
        return node;
    }
 
    public int? Min()
    {
        if (_root is null)
            return null;
        var node = _root;
        while (node.Left is not null)
            node = node.Left;
        return node.Key;
    }
 
    public int? Max()
    {
        if (_root is null)
            return null;
        var node = _root;
        while (node.Right is not null)
            node = node.Right;
        return node.Key;
    }
 
    /// <summary>Checks the invariant: every key lies strictly between the bounds set by all its ancestors.</summary>
    public bool IsValid() => IsValid(_root, null, null);
 
    private static bool IsValid(Node? node, int? low, int? high)
    {
        if (node is null)
            return true;
        if ((low is not null && node.Key <= low) || (high is not null && node.Key >= high))
            return false;
        return IsValid(node.Left, low, node.Key) && IsValid(node.Right, node.Key, high);
    }
 
    /// <summary>Keys in ascending order (inorder traversal).</summary>
    public List<int> InOrder()
    {
        var keys = new List<int>(Count);
        void Walk(Node? node)
        {
            if (node is null)
                return;
            Walk(node.Left);
            keys.Add(node.Key);
            Walk(node.Right);
        }
        Walk(_root);
        return keys;
    }
 
    /// <summary>Height in edges; -1 for an empty tree.</summary>
    public int Height()
    {
        static int Of(Node? node) => node is null ? -1 : 1 + Math.Max(Of(node.Left), Of(node.Right));
        return Of(_root);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Trees/BinarySearchTree.cs

"""An unbalanced binary search tree of distinct int keys.
 
Every key in a node's left subtree is smaller and every key in its right subtree
larger. insert, contains, remove, min and max cost O(h): O(log n) when the tree is
balanced, O(n) when it degenerates into a chain (e.g. keys inserted in sorted
order). The standard library has no balanced tree; sortedcontainers or bisect on
a sorted list are the usual substitutes.
"""
 
from __future__ import annotations
 
 
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 BinarySearchTree:
    def __init__(self) -> None:
        self._root: _Node | None = None
        self._count = 0
 
    def __len__(self) -> int:
        return self._count
 
    def insert(self, key: int) -> bool:
        """Add the key; return False if it is already present."""
        if self._root is None:
            self._root = _Node(key)
            self._count += 1
            return True
        node = self._root
        while True:
            cmp = (key > node.key) - (key < node.key)
            if cmp == 0:
                return False
            child = node.left if cmp < 0 else node.right
            if child is None:
                if cmp < 0:
                    node.left = _Node(key)
                else:
                    node.right = _Node(key)
                self._count += 1
                return True
            node = child
 
    def contains(self, key: int) -> bool:
        node = self._root
        while node is not None:
            cmp = (key > node.key) - (key < node.key)
            if cmp == 0:
                return True
            node = node.left if cmp < 0 else node.right
        return False
 
    def remove(self, key: int) -> bool:
        """Remove the key; return False if it was not present."""
        before = self._count
        self._root = self._remove(self._root, key)
        return self._count < before
 
    def _remove(self, node: _Node | None, key: int) -> _Node | None:
        """Delete key from the subtree and return the subtree's new root."""
        if node is None:
            return None
        if key < node.key:
            node.left = self._remove(node.left, key)
            return node
        if key > node.key:
            node.right = self._remove(node.right, key)
            return node
        if node.left is None:
            self._count -= 1
            return node.right  # a leaf returns None; otherwise the right child moves up
        if node.right is None:
            self._count -= 1
            return node.left
        successor = node.right
        while successor.left is not None:
            successor = successor.left
        node.key = successor.key
        node.right = self._remove(node.right, successor.key)
        return node
 
    def min(self) -> int | None:
        if self._root is None:
            return None
        node = self._root
        while node.left is not None:
            node = node.left
        return node.key
 
    def max(self) -> int | None:
        if self._root is None:
            return None
        node = self._root
        while node.right is not None:
            node = node.right
        return node.key
 
    def is_valid(self) -> bool:
        """Every key lies strictly between the bounds set by all its ancestors."""
        return _is_valid(self._root, None, None)
 
    def in_order(self) -> list[int]:
        keys: list[int] = []
 
        def walk(node: _Node | None) -> None:
            if node is not None:
                walk(node.left)
                keys.append(node.key)
                walk(node.right)
 
        walk(self._root)
        return keys
 
    def height(self) -> int:
        """Height in edges; -1 for an empty tree."""
 
        def of(node: _Node | None) -> int:
            return -1 if node is None else 1 + max(of(node.left), of(node.right))
 
        return of(self._root)
 
 
def _is_valid(node: _Node | None, low: int | None, high: int | None) -> bool:
    if node is None:
        return True
    if (low is not None and node.key <= low) or (high is not None and node.key >= high):
        return False
    return _is_valid(node.left, low, node.key) and _is_valid(node.right, node.key, high)

Tested on CPython 3.14.0 · examples/python/dsa_examples/bst.py

package dev.bekadan.dsa.trees;
 
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
 
/**
 * An unbalanced binary search tree of distinct int keys. Every key in a node's
 * left subtree is smaller and every key in its right subtree larger. insert,
 * contains, remove, min and max cost O(h): O(log n) when the tree is balanced,
 * O(n) when it degenerates into a chain (e.g. keys inserted in sorted order).
 * TreeSet and TreeMap keep the same contract balanced (red-black trees).
 */
public final class BinarySearchTree {
    private static final class Node {
        int key;
        Node left;
        Node right;
 
        Node(int key) {
            this.key = key;
        }
    }
 
    private Node root;
    private int count;
 
    public int size() {
        return count;
    }
 
    /** Adds the key; returns false if it is already present. */
    public boolean insert(int key) {
        if (root == null) {
            root = new Node(key);
            count++;
            return true;
        }
        Node node = root;
        while (true) {
            int cmp = Integer.compare(key, node.key);
            if (cmp == 0) {
                return false;
            }
            Node child = cmp < 0 ? node.left : node.right;
            if (child == null) {
                if (cmp < 0) {
                    node.left = new Node(key);
                } else {
                    node.right = new Node(key);
                }
                count++;
                return true;
            }
            node = child;
        }
    }
 
    public boolean contains(int key) {
        Node node = root;
        while (node != null) {
            int cmp = Integer.compare(key, node.key);
            if (cmp == 0) {
                return true;
            }
            node = cmp < 0 ? node.left : node.right;
        }
        return false;
    }
 
    /** Removes the key; returns false if it was not present. */
    public boolean remove(int key) {
        int before = count;
        root = remove(root, key);
        return count < before;
    }
 
    /** Deletes key from the subtree and returns the subtree's new root. */
    private Node remove(Node node, int key) {
        if (node == null) {
            return null;
        }
        int cmp = Integer.compare(key, node.key);
        if (cmp < 0) {
            node.left = remove(node.left, key);
            return node;
        }
        if (cmp > 0) {
            node.right = remove(node.right, key);
            return node;
        }
        if (node.left == null) {
            count--;
            return node.right; // a leaf returns null; otherwise the right child moves up
        }
        if (node.right == null) {
            count--;
            return node.left;
        }
        Node successor = node.right;
        while (successor.left != null) {
            successor = successor.left;
        }
        node.key = successor.key;
        node.right = remove(node.right, successor.key);
        return node;
    }
 
    public OptionalInt min() {
        if (root == null) {
            return OptionalInt.empty();
        }
        Node node = root;
        while (node.left != null) {
            node = node.left;
        }
        return OptionalInt.of(node.key);
    }
 
    public OptionalInt max() {
        if (root == null) {
            return OptionalInt.empty();
        }
        Node node = root;
        while (node.right != null) {
            node = node.right;
        }
        return OptionalInt.of(node.key);
    }
 
    /** Checks the invariant: every key lies strictly between the bounds set by all its ancestors. */
    public boolean isValid() {
        return isValid(root, null, null);
    }
 
    private static boolean isValid(Node node, Integer low, Integer high) {
        if (node == null) {
            return true;
        }
        if ((low != null && node.key <= low) || (high != null && node.key >= high)) {
            return false;
        }
        return isValid(node.left, low, node.key) && isValid(node.right, node.key, high);
    }
 
    /** Keys in ascending order (inorder traversal). */
    public List<Integer> inOrder() {
        List<Integer> keys = new ArrayList<>(count);
        walk(root, keys);
        return keys;
    }
 
    private static void walk(Node node, List<Integer> keys) {
        if (node == null) {
            return;
        }
        walk(node.left, keys);
        keys.add(node.key);
        walk(node.right, keys);
    }
 
    /** Height in edges; -1 for an empty tree. */
    public int height() {
        return height(root);
    }
 
    private static int height(Node node) {
        return node == null ? -1 : 1 + Math.max(height(node.left), height(node.right));
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/trees/BinarySearchTree.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// An unbalanced binary search tree of distinct int keys. Every key in a node's
// left subtree is smaller and every key in its right subtree larger. insert,
// contains, remove, min and max cost O(h): O(log n) when the tree is balanced,
// O(n) when it degenerates into a chain (e.g. keys inserted in sorted order).
// std::set keeps the same contract balanced (typically a red-black tree).
class BinarySearchTree {
public:
    [[nodiscard]] std::size_t size() const noexcept { return count_; }
 
    // Adds the key; returns false if it is already present.
    bool insert(int key) {
        if (!root_) {
            root_ = std::make_unique<Node>(key);
            ++count_;
            return true;
        }
        Node* node = root_.get();
        while (true) {
            const int cmp = (key > node->key) - (key < node->key);
            if (cmp == 0)
                return false;
            std::unique_ptr<Node>& child = cmp < 0 ? node->left : node->right;
            if (!child) {
                child = std::make_unique<Node>(key);
                ++count_;
                return true;
            }
            node = child.get();
        }
    }
 
    [[nodiscard]] bool contains(int key) const {
        const Node* node = root_.get();
        while (node) {
            const int cmp = (key > node->key) - (key < node->key);
            if (cmp == 0)
                return true;
            node = cmp < 0 ? node->left.get() : node->right.get();
        }
        return false;
    }
 
    // Removes the key; returns false if it was not present.
    bool remove(int key) {
        const std::size_t before = count_;
        root_ = remove(std::move(root_), key);
        return count_ < before;
    }
 
    [[nodiscard]] std::optional<int> min() const {
        if (!root_)
            return std::nullopt;
        const Node* node = root_.get();
        while (node->left)
            node = node->left.get();
        return node->key;
    }
 
    [[nodiscard]] std::optional<int> max() const {
        if (!root_)
            return std::nullopt;
        const Node* node = root_.get();
        while (node->right)
            node = node->right.get();
        return node->key;
    }
 
    // Checks the invariant: every key lies strictly between the bounds set by all its ancestors.
    [[nodiscard]] bool is_valid() const { return is_valid(root_.get(), std::nullopt, std::nullopt); }
 
    // Keys in ascending order (inorder traversal).
    [[nodiscard]] std::vector<int> in_order() const {
        std::vector<int> keys;
        keys.reserve(count_);
        walk(root_.get(), keys);
        return keys;
    }
 
    // Height in edges; -1 for an empty tree.
    [[nodiscard]] int height() const { return height(root_.get()); }
 
private:
    struct Node {
        int key;
        std::unique_ptr<Node> left;
        std::unique_ptr<Node> right;
        explicit Node(int k) : key(k) {}
    };
 
    std::unique_ptr<Node> root_;
    std::size_t count_ = 0;
 
    // Deletes key from the subtree and returns the subtree's new root.
    std::unique_ptr<Node> remove(std::unique_ptr<Node> node, int key) {
        if (!node)
            return nullptr;
        if (key < node->key) {
            node->left = remove(std::move(node->left), key);
            return node;
        }
        if (key > node->key) {
            node->right = remove(std::move(node->right), key);
            return node;
        }
        if (!node->left) {
            --count_;
            return std::move(node->right);  // a leaf returns nullptr; otherwise the right child moves up
        }
        if (!node->right) {
            --count_;
            return std::move(node->left);
        }
        const Node* successor = node->right.get();
        while (successor->left)
            successor = successor->left.get();
        node->key = successor->key;
        node->right = remove(std::move(node->right), node->key);
        return node;
    }
 
    static bool is_valid(const Node* node, std::optional<int> low, std::optional<int> high) {
        if (!node)
            return true;
        if ((low && node->key <= *low) || (high && node->key >= *high))
            return false;
        return is_valid(node->left.get(), low, node->key) && is_valid(node->right.get(), node->key, high);
    }
 
    static void walk(const Node* node, std::vector<int>& keys) {
        if (!node)
            return;
        walk(node->left.get(), keys);
        keys.push_back(node->key);
        walk(node->right.get(), keys);
    }
 
    static int height(const Node* node) { return node ? 1 + std::max(height(node->left.get()), height(node->right.get())) : -1; }
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_search_tree.hpp

Learn more

Problems, patterns and exercises

References