← All Posts
DSA Series · Trees · Part 3

Binary Search Trees (BST)

The BST Property

A BST enforces an ordering invariant: for every node, all values in the left subtree are smaller, and all values in the right subtree are larger. This enables O(log n) search, insert, and delete on balanced trees.

All values < 20 All values > 20 20 10 30 5 15 25 35
BST property: left subtree < root < right subtree, recursively.
function search(node, key):
if node == null: return null if key == node.val: return node if key < node.val: return search(node.left, key) return search(node.right, key)
Complexity: O(h) where h = height. For a balanced tree h = log n. For a skewed tree h = n.

▶ BST Search Animation

Watch how BST search navigates left or right at each node by comparing values.

20 10 30 5 15 25 35

BST Insertion

▶ BST Insertion Animation

Watch how value 13 finds its position by comparing at each level.

20 10 30 5 15 25 13
TreeNode* insert(TreeNode* root, int val) {
    if (!root) return new TreeNode(val);
    if (val < root->val)
        root->left = insert(root->left, val);
    else if (val > root->val)
        root->right = insert(root->right, val);
    return root;
}

BST Deletion

Three cases when deleting a node:

Case 1: Leaf 10 5 7 Just remove it Case 2: One Child 10 5 3 Replace with child Case 3: Two Children 10 5 15 12 Replace with in-order successor (12)
Three cases of BST deletion. Dashed = node being deleted.
TreeNode* deleteNode(TreeNode* root, int key) {
    if (!root) return nullptr;
    if (key < root->val) {
        root->left = deleteNode(root->left, key);
    } else if (key > root->val) {
        root->right = deleteNode(root->right, key);
    } else {
        if (!root->left) return root->right;
        if (!root->right) return root->left;
        TreeNode* successor = root->right;
        while (successor->left) successor = successor->left;
        root->val = successor->val;
        root->right = deleteNode(root->right, successor->val);
    }
    return root;
}

▶ BST Deletion Animation

See how each deletion case works. The tree resets each time.

Summary