M19 · Binary Search Trees

Binary Search Trees: Search, Insert, Delete and the Cost of Height

A binary search tree keeps keys in order without keeping them in an array: smaller keys to the left, larger to the right, at every node. One comparison per level is enough to find, insert or remove a key, so everything costs O(h). Whether h is about log n or about n depends only on the order the keys arrived in.

~45 minIntermediateC# · Python · Java · C++
Curriculum: M19 Binary Search Trees · 1 of 1 lessons available

You will be able to

  • State the BST invariant precisely (whole subtrees, not just children) and use it to rule out half of a subtree with one comparison.
  • Trace search, insert, min and max, and explain why each costs one comparison or step per level: O(h).
  • Delete a key in each of the three cases (leaf, one child, two children) and justify why copying the inorder successor keeps the tree valid.
  • Check whether a tree is a BST with inherited (low, high) bounds, and recognise the parent-only check that gets it wrong.
  • Relate height to insertion order: about log₂ n for balanced shapes, n − 1 for sorted input, and know which built-in ordered collections keep it logarithmic.

Helpful before this lesson

  • M18 Trees — Tree vocabulary, representations and every traversal, recursive and iterative.
  • M12 Searching — Linear and binary search and their relatives, with the preconditions each one needs.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Binary search needs a sorted array, and keeping an array sorted while keys come and go is expensive: every insert or delete shifts up to n elements. A binary search tree stores the same ordering in links instead of positions, so a new key only needs one new link.

Each node holds a key and up to two children. The whole structure obeys one rule, the BST invariant:

For every node x, every key in x's left subtree is smaller than x.key, and every key in its right subtree is larger.

"Every key in the subtree" is the important part. It is not enough for the left child to be smaller. In the tree below, 60 is larger than its parent 30, which looks fine locally, but it sits in the left subtree of 50, where every key must be below 50. That tree is not a BST, and a search for 60 would go right at the root and never find it.

        50
       /  \
     30    70
       \
        60      ← breaks the invariant: 60 > 50 but it is in 50's left subtree

Because of the invariant, comparing a key with one node tells you which subtree it could be in and rules out the other subtree completely, much like one comparison in binary search rules out half of the remaining range. The lab lays nodes out left to right in sorted order and one row per level, so you can see both facts at once: the row is the depth, and reading the keys left to right gives the inorder sequence, which is always sorted.

This lesson's tree stores a set of distinct integers. Inserting a key that is already there changes nothing and returns false. Real trees often store key/value pairs and replace the value instead, or allow duplicates by sending equal keys consistently to one side; pick one policy and keep it, or searches and deletes will disagree with inserts.

Start at the root and compare; go left on smaller, right on larger, stop on equal or when the link you need is empty.

node = root
while node != null:
    if key == node.key: return true
    node = key < node.key ? node.left : node.right
return false

Every iteration moves one level down, so a search makes at most h + 1 comparisons, where h is the tree's height (the number of edges on the longest root-to-leaf path; −1 for an empty tree, 0 for a single node). When a search fails, the empty link it fell off is exactly where that key belongs. Insert relies on this.

Minimum and maximum need no comparisons at all: the smallest key is the leftmost node, so keep following left links until there is none; the largest is the rightmost. Both are O(h).

The inorder successor of a key (the next larger key) is the minimum of its right subtree when it has one; otherwise it is the nearest ancestor whose left subtree contains the key. The predecessor is the mirror image. Delete uses the first rule.

Insert

Insert is a search that does not give up at an empty link: it attaches a new leaf there.

if root == null: root = new Node(key); return true
node = root
loop:
    if key == node.key: return false          # already present
    child = key < node.key ? node.left : node.right
    if child == null:
        attach new Node(key) on that side of node; return true
    node = child

Inserting never moves an existing node, which is why the invariant survives: the new key is placed where a search for it would look, and every ancestor on that path compared it correctly. The flip side is that the shape of the tree is decided entirely by the order of the inserts. Run the presets Sorted inserts: degenerate and Same keys, balanced order in the lab: the same kind of keys produce a chain of height 5 in one and a perfect tree of height 2 in the other.

Delete: three cases

Finding the node is a search. Removing it depends on how many children it has. The implementation here is recursive: delete(node, key) returns the root of the subtree after the deletion, and each caller stores that value back into the link it came from. That one convention handles "the deleted node was the root" and "the deleted node was a left/right child" in the same way.

  1. Leaf (no children). Return null: the parent's link simply disappears.
  2. One child. Return that child. It takes the deleted node's place, and its whole subtree moves up one level. Nothing inside the subtree changes, so it stays ordered, and every key in it was already on the correct side of every ancestor.
  3. Two children. The node cannot just vanish: two subtrees would need one parent link. Instead, find the inorder successor s, the leftmost node of the right subtree. Copy s.key into the node, then delete s.key from the right subtree.

Why does case 3 keep the invariant? s.key is the smallest key in the right subtree, so it is larger than everything in the left subtree (they were all smaller than the old key) and smaller than everything else on the right. It is a valid key for that position. And deleting s afterwards is always case 1 or 2, because the leftmost node of a subtree has no left child. The lab marks the node being replaced and walks the successor search one link at a time: one step right, then left until there is no left child. Between the copy and the second delete, s.key briefly exists twice; the lab shows that too.

delete(node, key):
    if node == null: return null                       # key not present
    if key < node.key: node.left  = delete(node.left, key);  return node
    if key > node.key: node.right = delete(node.right, key); return node
    if node.left  == null: return node.right            # cases 1 and 2
    if node.right == null: return node.left             # case 2
    s = node.right; while s.left != null: s = s.left    # case 3: successor
    node.key = s.key
    node.right = delete(node.right, s.key)
    return node

Using the predecessor (rightmost of the left subtree) works just as well. Always choosing the same side is asymmetric, and over long runs of random inserts and deletes it is known to skew trees away from balance; some implementations alternate. Balanced trees (module M20) remove the question by rebalancing after each change.

The preset Delete: three cases removes a leaf, a one-child node and a two-child node in that order, then validates the result.

Validating a tree

The tempting check compares each node only with its children. It passes the broken tree at the top of this lesson, because 30 < 60 locally. The correct check passes down the bounds that every ancestor imposes:

valid(node, low, high):
    if node == null: return true
    if (low != null and node.key <= low) or (high != null and node.key >= high): return false
    return valid(node.left, low, node.key) and valid(node.right, node.key, high)

valid(root, null, null)

Going left lowers the upper bound to the current key; going right raises the lower bound. Each node is checked once: O(n) time, O(h) stack. An equivalent check is "an inorder traversal produces a strictly increasing sequence", which is the same fact seen from the other side. The check operation in the lab shows the interval each node must fall into.

Cost: it is all about height

Search, insert, delete, min and max each walk one root-to-leaf path (delete may walk a second, shorter one inside the right subtree), so each costs O(h) time. The iterative search and insert use O(1) extra space; the recursive delete uses O(h) stack.

Shape Height h Search / insert / delete
Perfectly balanced (n = 2ᵏ − 1) ⌊log₂ n⌋ O(log n)
Keys inserted in random order (expected) O(log n); the average depth is about 1.39 log₂ n O(log n) expected
Keys inserted in sorted or reverse-sorted order n − 1 (a chain) O(n): a linked list with extra steps

The lower bound comes from counting: a binary tree of height h holds at most 2^(h+1) − 1 nodes, so h ≥ ⌈log₂(n + 1)⌉ − 1. The upper bound is a chain. Real input is often partly sorted (timestamps, auto-increment IDs, alphabetical imports), which is exactly the bad case, so a plain BST is rarely used directly in production. Balanced variants (AVL, red-black, B-trees) keep h = O(log n) regardless of order, at the price of rotations or splits on update.

Recursion depth follows height too. On a degenerate tree with a hundred thousand keys, the recursive delete and validation would need a hundred thousand stack frames: beyond CPython's default recursion limit (1,000) and risky in C#, Java and C++ as well. Iterative versions or a balanced tree avoid this.

Built-in ordered collections

None of the four languages exposes a plain BST, and none needs to:

Language Ordered set / map Guarantee
C# SortedSet<T>, SortedDictionary<TKey,TValue> red-black tree; O(log n) add, remove, lookup; Min, Max, GetViewBetween
Java TreeSet<E>, TreeMap<K,V> red-black tree; O(log n) add, remove, contains; floor, ceiling, higher, lower
C++ std::set, std::map O(log n) insert, erase, find (usually red-black); lower_bound, upper_bound
Python none in the standard library bisect on a sorted list gives O(log n) search but O(n) insertion; third-party sorted containers fill the gap

The floor/ceiling/lower_bound family answers "the nearest key at or below / above x", the question a hash table cannot answer and the main reason to choose an ordered structure over a hash one.

The teaching implementation

Insert/insert and Contains/contains are iterative; Remove and the invariant check are recursive, the same structure in all four languages so the lab can highlight matching lines.

  • C# and Java compare with CompareTo / Integer.compare, which also works for any comparable key type. Java returns OptionalInt from min/max, C# returns int?.
  • Python computes a three-way comparison as (key > node.key) - (key < node.key) to mirror the other languages; idiomatic Python would just use < and ==.
  • C++ owns nodes through std::unique_ptr, so removing a node frees it automatically, and insert binds a reference to the empty unique_ptr link and assigns the new node into it. min/max return std::optional<int>.

Every language runs one shared fixture (all three delete cases, a successor deep in the right subtree, a successor with a right child, duplicates, missing keys, an empty tree, a degenerate chain, extreme keys), checks the invariant after every operation, and compares 300 random runs of 60 operations with a sorted-list model.

Common mistakes

  • Checking only parent–child pairs when validating. Pass bounds down instead.
  • Forgetting to store the returned subtree in the recursive delete (delete(node.left, key) without node.left = …). The node is "deleted" from a copy of the link and stays in the tree.
  • Deleting the successor from the wrong subtree. After copying, delete s.key from node.right, not from the root: from the root the search would stop at the node you just copied into.
  • Inconsistent duplicate policy, for example inserting equal keys to the right but searching or deleting as if they went left.
  • Assuming O(log n). Without balancing, sorted input makes every operation linear.

Edge cases

  • Empty tree: search and delete return false, min and max return nothing, validation succeeds.
  • Deleting the root: works through the same "return the new subtree root" rule; with two children the root keeps its node and only its key changes.
  • Deleting the only node: the tree becomes empty (case 1 at the root).
  • Successor is the right child itself (it has no left child): the copy is followed by a case 1 or 2 delete one level down.
  • Extreme keys (int.MinValue, int.MaxValue): the bounds in the validator are nullable rather than sentinel values, so no key is treated as "out of range" by accident.

Worked practice

1. Insert 8, 3, 10, 1, 6, 14, 4, 7, 13 into an empty tree. What is its height, and how many comparisons does a search for 13 make?

Answer

Height 3 (8 → 3 → 6 → 4, or 8 → 10 → 14 → 13). Searching 13 compares with 8, 10, 14 and 13: four comparisons.

2. In that tree, delete 3. Which key replaces it, and what does the tree look like afterwards?

Answer

3 has two children, so take its successor: one step right to 6, then left to 4, which has no left child. Copy 4 into the node, then delete 4 from 3's old right subtree (it is a leaf). The left subtree of 8 becomes 4 with children 1 and 6, and 6 keeps its right child 7.

3. Is this tree a BST: root 10, left child 5 (whose right child is 12), right child 15?

Answer

No. 12 is in 10's left subtree, so it must be below 10. The bounds check gives 12 the interval (5, 10) and rejects it; a parent-only check would accept it because 12 > 5.

4. You must insert the keys 1…1,000 (already sorted) and then answer lookups. What goes wrong with a plain BST, and what are two fixes?

Answer

The tree becomes a chain of height 999, so each lookup costs up to 1,000 comparisons, and recursive operations risk deep recursion. Fixes: build a balanced tree directly from the sorted list (take the middle element as the root, recurse on each half, O(n)), or use a self-balancing tree such as SortedSet, TreeMap or std::set. Inserting in shuffled order also gives O(log n) expected height.

Summary

  • The invariant covers whole subtrees: everything left of a node is smaller, everything right is larger. Inorder traversal therefore yields sorted order.
  • Search, insert, min and max follow one path: O(h). Insert attaches a leaf where search failed.
  • Delete has three cases; with two children, copy the inorder successor's key and delete the successor, which has at most one child.
  • Validate with inherited bounds, not parent–child comparisons.
  • h ranges from ⌊log₂ n⌋ to n − 1 depending on insertion order. Production code uses balanced trees (SortedSet, TreeMap, std::set) to guarantee O(log n).

Full implementation

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

References