Trees · O(h): O(log n) balanced, O(n) degenerate

Binary search tree

Insert, search and delete (all three cases) while the ordering invariant holds.

The full explanation, derivation and practice are in the lesson Binary search trees: search, insert, delete and the cost of height.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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