C++ · Module 18 · Lesson 41 min read

Binary Search Trees

The BST rule

For every node: all values in the left subtree are smaller, all values in the right subtree are larger.

markdown
        50
       /  \
     30    70
    / \    / \
   20 40  60  80

Operations

OperationHowAverageWorst
Searchgo left if smaller, right if largerO(log n)O(n)
Insertsearch for the spot, attach a new leafO(log n)O(n)
Min / Maxleftmost / rightmost nodeO(log n)O(n)
Delete3 cases (below)O(log n)O(n)
In-order traversalleft, node, right → sorted outputO(n)O(n)

Deleting a node

  1. Leaf → remove it
  2. One child → replace the node with its child
  3. Two children → copy the in-order successor (smallest in the right subtree) into the node, then delete the successor

Traversals

  • In-order (L, N, R): sorted order
  • Pre-order (N, L, R): copy/serialize a tree
  • Post-order (L, R, N): delete a tree, evaluate expression trees
  • Level-order (BFS with a queue): level by level

Height and balance ⚠️

Inserting already-sorted data (1, 2, 3, 4…) produces a "linked list" tree of height n → O(n) operations. Self-balancing trees (AVL, red-black) rotate nodes to keep height O(log n) — std::map uses a red-black tree.

Implementation notes

Using std::unique_ptr<Node> for children makes cleanup automatic; recursion makes insert/search/traversal short and clear.

Example

C++
#include <iostream>
#include <memory>
#include <queue>
#include <vector>

class BST {
    struct Node {
        int key;
        std::unique_ptr<Node> left, right;
        explicit Node(int k) : key(k) {}
    };
public:
    bool insert(int key) { return insert(root_, key); }
    bool contains(int key) const {
        const Node* n = root_.get();
        while (n) {
            if (key == n->key) return true;
            n = key < n->key ? n->left.get() : n->right.get();
        }
        return false;
    }
    void erase(int key) { erase(root_, key); }
    std::vector<int> in_order() const { std::vector<int> out; in_order(root_.get(), out); return out; }
    int height() const { return height(root_.get()); }
    void print_levels() const {
        std::queue<const Node*> q;
        if (root_) q.push(root_.get());
        while (!q.empty()) {
            std::size_t level_size = q.size();
            for (std::size_t i = 0; i < level_size; ++i) {
                const Node* n = q.front(); q.pop();
                std::cout << n->key << ' ';
                if (n->left) q.push(n->left.get());
                if (n->right) q.push(n->right.get());
            }
            std::cout << "| ";
        }
        std::cout << '\n';
    }
private:
    static bool insert(std::unique_ptr<Node>& n, int key) {
        if (!n) { n = std::make_unique<Node>(key); return true; }
        if (key == n->key) return false;                               // no duplicates
        return insert(key < n->key ? n->left : n->right, key);
    }
    static void erase(std::unique_ptr<Node>& n, int key) {
        if (!n) return;
        if (key < n->key) return erase(n->left, key);
        if (key > n->key) return erase(n->right, key);
        if (!n->left) { n = std::move(n->right); return; }             // 0 or 1 child
        if (!n->right) { n = std::move(n->left); return; }
        Node* succ = n->right.get();                                    // 2 children: in-order successor
        while (succ->left) succ = succ->left.get();
        n->key = succ->key;
        erase(n->right, succ->key);
    }
    static void in_order(const Node* n, std::vector<int>& out) {
        if (!n) return;
        in_order(n->left.get(), out);
        out.push_back(n->key);
        in_order(n->right.get(), out);
    }
    static int height(const Node* n) { return n ? 1 + std::max(height(n->left.get()), height(n->right.get())) : 0; }
    std::unique_ptr<Node> root_;
};

int main() {
    BST tree;
    for (int k : { 50, 30, 70, 20, 40, 60, 80, 35 }) tree.insert(k);
    std::cout << "duplicate 40 inserted? " << std::boolalpha << tree.insert(40) << '\n';

    std::cout << "in-order (sorted):";
    for (int k : tree.in_order()) std::cout << ' ' << k;
    std::cout << "\nlevels: ";
    tree.print_levels();
    std::cout << "contains 60? " << tree.contains(60) << ", contains 65? " << tree.contains(65) << '\n';

    tree.erase(20);      // leaf
    tree.erase(40);      // one child (35)
    tree.erase(50);      // two children: replaced by successor 60
    std::cout << "after erasing 20, 40, 50:";
    for (int k : tree.in_order()) std::cout << ' ' << k;
    std::cout << "\nlevels: ";
    tree.print_levels();

    BST skewed;
    for (int k = 1; k <= 8; ++k) skewed.insert(k);   // sorted input -> degenerate tree
    std::cout << "height with random-ish input: " << tree.height() << ", with sorted input: " << skewed.height() << '\n';
    return 0;
}

/* Output:
duplicate 40 inserted? false
in-order (sorted): 20 30 35 40 50 60 70 80
levels: 50 | 30 70 | 20 40 60 80 | 35 |
contains 60? true, contains 65? false
after erasing 20, 40, 50: 30 35 60 70 80
levels: 60 | 30 70 | 35 80 |
height with random-ish input: 3, with sorted input: 8
*/