CC Explainer
C · 4 · Dynamic Memory & Data Structures22 / 35 · 63%

Binary Search Trees

Ordered data with O(log n) search — when the tree stays balanced.

Examples: insert, search, recursion, free

shortcuts: ← prev · → next · M mark
1

The Node

Two children, one value.

Example
example
typedef struct Node {
    int value;
    struct Node *left, *right;
} Node;
2

Insert

Recurse left for smaller, right for larger.

Example
example
Node *insert(Node *root, int v) {
    if (!root) {
        Node *n = malloc(sizeof *n);
        n->value = v; n->left = n->right = NULL;
        return n;
    }
    if (v < root->value) root->left  = insert(root->left,  v);
    else if (v > root->value) root->right = insert(root->right, v);
    return root;
}
3

Traversal & Cleanup

In-order visits values in sorted order; post-order is how you free.

Example
example
void inorder(const Node *n) {
    if (!n) return;
    inorder(n->left);
    printf("%d ", n->value);
    inorder(n->right);
}

void destroy(Node *n) {
    if (!n) return;
    destroy(n->left); destroy(n->right);
    free(n);            // children first, then self
}
4

Balance Matters

Insert sorted data into a plain BST and it degenerates into a linked list.

Complexity
search (balanced)O(log n)
search (degenerate)O(n)sorted inserts
insertO(h)h = height
in-order traversalO(n)
TIP
Production code uses a self-balancing tree (AVL or red-black) — that's what std::map is.