# Binary Search Tree (BST) in C++: Search, Insert, Delete & Complete Guide

> Binary search tree in C++: the BST property, search, insert, all three deletion cases with diagrams, successor, validation and complexity, with tested code.

- Canonical URL: https://shafinchowdhury.dev/posts/binary-search-tree-bst/
- Author: Shafin Chowdhury (https://shafinchowdhury.dev/about/)
- Published: 2026-12-04T03:05:00.000Z
- Updated: 2026-12-04T03:05:00.000Z
- Reading Time: 13 min read
- Tags: cpp, data-structures, trees, binary-search-tree, beginners

---

import Diagram from "@/components/Diagram.astro";
import TraversalPlayer from "@/components/TraversalPlayer.astro";

A **binary search tree (BST)** is a binary tree with one extra rule: for every node, all keys in its **left subtree are smaller** and all keys in its **right subtree are larger**. That rule lets search, insertion and deletion skip half of the remaining tree at each step, so they run in $O(h)$ time, where $h$ is the height: $O(\log n)$ when the tree is balanced, $O(n)$ when it degenerates into a chain. An inorder traversal of a BST prints its keys in sorted order.

This guide implements every core BST operation in C++, recursively and iteratively, with diagrams for the cases students most often get wrong, especially **deleting a node with two children**.

> **Tree & Graph series, step 2 of 8.** Previous: [Trees, Binary Trees & Traversals](/posts/tree-binary-tree-traversals/). Next: [Tree Interview Questions](/posts/tree-interview-questions/). All parts: [Trees & Graphs](/topics/trees-graphs/).

---

## What Is a Binary Search Tree?

A **Binary Search Tree (BST)** is a type of [binary tree](/posts/tree-binary-tree-traversals/) data structure in which each node contains a unique key and satisfies a specific ordering property:

- All nodes in the **left subtree** of a node contain values **strictly less** than the node's value.
- All nodes in the **right subtree** of a node contain values **strictly greater** than the node's value.

This structure enables efficient operations for searching, insertion, and deletion of elements, especially when the tree remains balanced.

Because of this ordering, a search can decide at each node whether to go left or right, exactly like binary search on a sorted array decides which half to keep.

Throughout this article we use the BST built by inserting these keys in this order:

```text
50, 30, 70, 20, 40, 60, 80, 65
```

<Diagram
  src="binary-search-tree-bst/bst-property"
  alt="BST with root 50. Left subtree: 30 with children 20 and 40, boxed and labelled all less than 50. Right subtree: 70 with children 60 and 80, and 65 as the right child of 60, boxed and labelled all greater than 50."
/>

## BST Properties

For **every** node `x` in a BST:

1. Every key in `x`'s left subtree is **less than** `x->key`.
2. Every key in `x`'s right subtree is **greater than** `x->key`.
3. The left and right subtrees are themselves BSTs.

Consequences you should know:

- **Inorder traversal gives sorted order.** For our tree: `20 30 40 50 60 65 70 80`.
- The **minimum** is the leftmost node; the **maximum** is the rightmost node.
- The property is about **whole subtrees**, not just direct children. 65 is in 50's right subtree, so it must be greater than 50 even though its parent is 60.
- **Duplicates** need a policy. This guide ignores duplicate inserts (a set). Other options: always send equal keys right, or store a count in each node.

### Why does inorder traversal produce sorted output?

Inorder visits a node's left subtree, then the node, then its right subtree. By the BST property, everything in the left subtree is smaller than the node and everything in the right subtree is larger. So the node is printed after all smaller keys under it and before all larger keys under it. The same argument applies inside each subtree, so by induction (on subtree size) every key is printed after all keys smaller than it, which is exactly sorted order.

## BST vs Binary Tree

| | Binary tree | Binary search tree |
| --- | --- | --- |
| Structure rule | At most 2 children | At most 2 children **plus** the ordering rule |
| Search for a key | Check every node: $O(n)$ | Follow one path: $O(h)$ |
| Inorder traversal | No special order | Sorted order |
| Insert position | Anywhere you choose | Exactly one valid position for a new key |
| Typical use | Expression trees, heaps, hierarchies | Sets, maps, ordered dictionaries |

Every BST is a binary tree; most binary trees are not BSTs.

## How a BST Works

Every operation starts at the root and repeats one decision:

- target < current key → go **left**
- target > current key → go **right**
- target == current key → **found**

Because each step moves one level down, the work is proportional to the height of the tree, not the number of nodes. Step through the traversals of our BST here; notice that the inorder output comes out sorted:

<TraversalPlayer
  bst={[50, 30, 70, 20, 40, 60, 80, 65]}
  orders={["inorder", "preorder", "postorder", "levelorder"]}
  caption="Traversals of the BST built from 50, 30, 70, 20, 40, 60, 80, 65. Inorder produces the sorted sequence."
/>

## Search Operation

<Diagram
  src="binary-search-tree-bst/bst-search-path"
  alt="Two copies of the BST. Left: searching 65 highlights the path 50, 70, 60, 65 and finds 65. Right: searching 55 highlights 50, 70, 60, then reaches an empty left child of 60, so 55 is not found."
/>

**Search 65:**

- 65 > 50 → go right to 70.
- 65 < 70 → go left to 60.
- 65 > 60 → go right to 65.
- 65 = 65 → **found** after 4 comparisons.

**Search 55:**

- 55 > 50 → go right to 70.
- 55 < 70 → go left to 60.
- 55 < 60 → go left, but the left child of 60 is `nullptr`.
- **Not found.** Reaching `nullptr` proves the key is absent, because that is the only place it could have been.

```cpp excerpt
// Recursive search: returns the node holding key, or nullptr.
Node* search(Node* root, int key) {
    if (root == nullptr || root->key == key) {
        return root; // base cases
    }
    if (key < root->key) {
        return search(root->left, key);
    }
    return search(root->right, key);
}
```

```cpp excerpt
// Iterative search: same path, no recursion, O(1) extra space.
Node* searchIterative(Node* root, int key) {
    while (root != nullptr && root->key != key) {
        root = (key < root->key) ? root->left : root->right;
    }
    return root;
}
```

## Insertion Operation

A new key is always inserted as a **new leaf**. Search for the key; the `nullptr` where the search stops is exactly where the key belongs.

<Diagram
  src="binary-search-tree-bst/bst-insertion-steps"
  alt="Eight small trees showing the BST after inserting 50, 30, 70, 20, 40, 60, 80 and 65 in turn. In each frame the comparison path is highlighted and the newly inserted node is drawn with a dashed outline."
/>

Insert 65 into the tree that already holds 50, 30, 70, 20, 40, 60, 80: 65 > 50 → right, 65 < 70 → left, 65 > 60 → right, which is empty. Attach 65 as the **right child of 60**.

```cpp excerpt
// Recursive insert: returns the (possibly new) root of this subtree.
Node* insert(Node* root, int key) {
    if (root == nullptr) {
        return new Node(key); // empty spot found: new leaf
    }
    if (key < root->key) {
        root->left = insert(root->left, key);   // reconnect the left subtree
    } else if (key > root->key) {
        root->right = insert(root->right, key); // reconnect the right subtree
    }
    // key == root->key: duplicate, ignore it
    return root;
}
```

The line `root->left = insert(root->left, key);` is what **connects** the new node: the recursive call returns the new leaf when it reaches `nullptr`, and the parent stores it in the correct child pointer. Every other level just stores back the pointer it already had.

The iterative version keeps a `parent` pointer, because when the loop ends at `nullptr` we need to know whose child the new node becomes:

```cpp excerpt
Node* insertIterative(Node* root, int key) {
    Node* fresh = new Node(key);
    if (root == nullptr) {
        return fresh;
    }

    Node* parent = nullptr;
    Node* current = root;
    while (current != nullptr) {
        parent = current;
        if (key < current->key) {
            current = current->left;
        } else if (key > current->key) {
            current = current->right;
        } else { // duplicate
            delete fresh;
            return root;
        }
    }
    if (key < parent->key) {
        parent->left = fresh;
    } else {
        parent->right = fresh;
    }
    return root;
}
```

## Deletion Operation

Deletion is the hardest BST operation because removing a node must leave a valid BST. First search for the node, then handle one of three cases depending on how many children it has.

### Case 1: deleting a leaf node

<Diagram
  src="binary-search-tree-bst/bst-delete-leaf"
  alt="Deleting leaf 20: before, 20 is highlighted in red as the left child of 30. After, 30 has no left child and the rest of the tree is unchanged."
/>

A leaf has no children, so nothing depends on it. Free it and set the parent's pointer to `nullptr`. Deleting 20 makes `30->left = nullptr`.

### Case 2: deleting a node with one child

<Diagram
  src="binary-search-tree-bst/bst-delete-one-child"
  alt="Deleting 60, which has only a right child 65: before, 60 is red and 65 is highlighted. After, 65 is the left child of 70 in 60's old position."
/>

The node has exactly one subtree. **Splice it out**: connect its parent directly to its only child. Deleting 60 makes `70->left = 65`.

Why is this safe? 65's subtree was already inside 60's position, which lies inside 70's left subtree and 50's right subtree. Every key in it already satisfies all of those ancestors' constraints, so moving the whole subtree up one level keeps the BST property.

### Case 3: deleting a node with two children

<Diagram
  src="binary-search-tree-bst/bst-delete-two-children"
  alt="Deleting the root 50, which has two children. Before: 50 in red and its inorder successor 60 highlighted. After: the root holds 60, and 65 has moved up to be the left child of 70."
/>

Here we cannot splice the node out: its parent has only one pointer available but there are two subtrees to reattach. Instead, **replace the node's key** with a key that can legally sit in its position:

- the **inorder successor**: the smallest key in the right subtree (go right once, then left as far as possible), or
- the **inorder predecessor**: the largest key in the left subtree.

The successor of 50 is 60. It is larger than everything on the left (it came from the right subtree) and smaller than everything else on the right (it is the minimum there), so it is the perfect replacement.

Steps to delete 50:

1. Find the successor: go to 70, then left to 60. 60 has no left child, so it is the minimum.
2. Copy 60 into the root.
3. Delete the old 60 from the right subtree. The successor **never has a left child** (otherwise that child would be smaller), so this second deletion is always case 1 or case 2. Here it is case 2: 65 moves up.

Result: root 60, inorder `20 30 40 60 65 70 80`, still sorted.

```cpp excerpt
Node* deleteNode(Node* root, int key) {
    if (root == nullptr) {
        return nullptr;              // key not found
    }
    if (key < root->key) {
        root->left = deleteNode(root->left, key);
    } else if (key > root->key) {
        root->right = deleteNode(root->right, key);
    } else {
        // Cases 1 and 2: at most one child. Return the other side to the parent.
        if (root->left == nullptr) {
            Node* child = root->right;
            delete root;
            return child;
        }
        if (root->right == nullptr) {
            Node* child = root->left;
            delete root;
            return child;
        }
        // Case 3: two children. Copy the successor, then delete it from the right.
        Node* successor = findMin(root->right);
        root->key = successor->key;
        root->right = deleteNode(root->right, successor->key);
    }
    return root;
}
```

A leaf has both children `nullptr`, so the first `if` handles it and returns `nullptr` to the parent; cases 1 and 2 share code.

## Find Minimum and Maximum

The minimum is the leftmost node (keep going left); the maximum is the rightmost node.

```cpp excerpt
Node* findMin(Node* root) {
    while (root != nullptr && root->left != nullptr) {
        root = root->left;
    }
    return root;
}

Node* findMax(Node* root) {
    while (root != nullptr && root->right != nullptr) {
        root = root->right;
    }
    return root;
}
```

For our tree: min 20, max 80. Both take $O(h)$.

## Inorder Predecessor and Successor

The **successor** of a key is the next larger key in sorted order; the **predecessor** is the next smaller one.

- If the node has a **right subtree**, the successor is the minimum of that subtree. succ(50) = 60.
- If it has **no right subtree**, the successor is the nearest **ancestor** for which the node lies in the left subtree. succ(65) = 70: 65 is in 70's left subtree.

A simple way to handle both cases is to walk from the root and remember the last node where you turned left:

```cpp excerpt
// Smallest key greater than `key` (works even if key is not in the tree).
Node* successor(Node* root, int key) {
    Node* best = nullptr;
    while (root != nullptr) {
        if (key < root->key) {
            best = root;        // candidate; try to find a smaller one on the left
            root = root->left;
        } else {
            root = root->right;
        }
    }
    return best;
}

// Largest key smaller than `key`.
Node* predecessor(Node* root, int key) {
    Node* best = nullptr;
    while (root != nullptr) {
        if (key > root->key) {
            best = root;
            root = root->right;
        } else {
            root = root->left;
        }
    }
    return best;
}
```

## Find the Height of a BST

Height is computed exactly as for any binary tree, in $O(n)$, because it needs every path:

```cpp excerpt
int height(Node* root) {
    if (root == nullptr) {
        return -1; // edges convention: a single node has height 0
    }
    return 1 + max(height(root->left), height(root->right));
}
```

Our tree has height 3 (path 50 → 70 → 60 → 65).

## Validate Whether a Tree Is a BST

The classic mistake is to check only that `left->key < node->key < right->key` at each node. That misses violations deeper down. Instead, pass down the **range** of keys allowed in each subtree:

```cpp excerpt
// Every key in this subtree must be strictly between low and high.
bool isBST(Node* root, long long low, long long high) {
    if (root == nullptr) {
        return true;
    }
    if (root->key <= low || root->key >= high) {
        return false;
    }
    return isBST(root->left, low, root->key) &&
           isBST(root->right, root->key, high);
}
```

Call it as `isBST(root, LLONG_MIN, LLONG_MAX)`. Using `long long` bounds avoids a bug when a key equals `INT_MIN` or `INT_MAX`. An alternative is to do an inorder traversal and check that each key is greater than the previous one. The [BST interview questions guide](/posts/bst-interview-questions/) shows a tree that fools the parent-child check.

## Build a BST From an Array

**Unsorted array:** insert each element in order. The shape depends entirely on the order. $O(n \cdot h)$ total, which is $O(n^2)$ in the worst case.

**Sorted array:** do not insert one by one, because that creates a chain. Instead pick the **middle** element as the root and build the two halves recursively. The result is height-balanced and takes $O(n)$:

```cpp excerpt
Node* buildBalanced(const vector<int>& sorted, int lo, int hi) {
    if (lo > hi) {
        return nullptr;
    }
    int mid = lo + (hi - lo) / 2;
    Node* root = new Node(sorted[mid]);
    root->left = buildBalanced(sorted, lo, mid - 1);
    root->right = buildBalanced(sorted, mid + 1, hi);
    return root;
}
```

## Complete C++ Program: Search, Insert and Delete

Everything above in one program. It builds our example tree, exercises each operation, and applies each deletion case to a fresh copy of the tree so the output matches the diagrams.

```cpp
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;

struct Node {
    int key;
    Node* left;
    Node* right;
    explicit Node(int k) : key(k), left(nullptr), right(nullptr) {}
};

// Recursive insert: returns the (possibly new) root of this subtree.
Node* insert(Node* root, int key) {
    if (root == nullptr) {
        return new Node(key); // empty spot found: new leaf
    }
    if (key < root->key) {
        root->left = insert(root->left, key);   // reconnect the left subtree
    } else if (key > root->key) {
        root->right = insert(root->right, key); // reconnect the right subtree
    }
    // key == root->key: duplicate, ignore it
    return root;
}

Node* insertIterative(Node* root, int key) {
    Node* fresh = new Node(key);
    if (root == nullptr) {
        return fresh;
    }

    Node* parent = nullptr;
    Node* current = root;
    while (current != nullptr) {
        parent = current;
        if (key < current->key) {
            current = current->left;
        } else if (key > current->key) {
            current = current->right;
        } else { // duplicate
            delete fresh;
            return root;
        }
    }
    if (key < parent->key) {
        parent->left = fresh;
    } else {
        parent->right = fresh;
    }
    return root;
}

// Recursive search: returns the node holding key, or nullptr.
Node* search(Node* root, int key) {
    if (root == nullptr || root->key == key) {
        return root; // base cases
    }
    if (key < root->key) {
        return search(root->left, key);
    }
    return search(root->right, key);
}

// Iterative search: same path, no recursion, O(1) extra space.
Node* searchIterative(Node* root, int key) {
    while (root != nullptr && root->key != key) {
        root = (key < root->key) ? root->left : root->right;
    }
    return root;
}

Node* findMin(Node* root) {
    while (root != nullptr && root->left != nullptr) {
        root = root->left;
    }
    return root;
}

Node* findMax(Node* root) {
    while (root != nullptr && root->right != nullptr) {
        root = root->right;
    }
    return root;
}

Node* deleteNode(Node* root, int key) {
    if (root == nullptr) {
        return nullptr;              // key not found
    }
    if (key < root->key) {
        root->left = deleteNode(root->left, key);
    } else if (key > root->key) {
        root->right = deleteNode(root->right, key);
    } else {
        // Cases 1 and 2: at most one child. Return the other side to the parent.
        if (root->left == nullptr) {
            Node* child = root->right;
            delete root;
            return child;
        }
        if (root->right == nullptr) {
            Node* child = root->left;
            delete root;
            return child;
        }
        // Case 3: two children. Copy the successor, then delete it from the right.
        Node* successor = findMin(root->right);
        root->key = successor->key;
        root->right = deleteNode(root->right, successor->key);
    }
    return root;
}

// Smallest key greater than `key` (works even if key is not in the tree).
Node* successor(Node* root, int key) {
    Node* best = nullptr;
    while (root != nullptr) {
        if (key < root->key) {
            best = root;        // candidate; try to find a smaller one on the left
            root = root->left;
        } else {
            root = root->right;
        }
    }
    return best;
}

// Largest key smaller than `key`.
Node* predecessor(Node* root, int key) {
    Node* best = nullptr;
    while (root != nullptr) {
        if (key > root->key) {
            best = root;
            root = root->right;
        } else {
            root = root->left;
        }
    }
    return best;
}

int height(Node* root) {
    if (root == nullptr) {
        return -1; // edges convention: a single node has height 0
    }
    return 1 + max(height(root->left), height(root->right));
}

// Every key in this subtree must be strictly between low and high.
bool isBST(Node* root, long long low, long long high) {
    if (root == nullptr) {
        return true;
    }
    if (root->key <= low || root->key >= high) {
        return false;
    }
    return isBST(root->left, low, root->key) &&
           isBST(root->right, root->key, high);
}

Node* buildBalanced(const vector<int>& sorted, int lo, int hi) {
    if (lo > hi) {
        return nullptr;
    }
    int mid = lo + (hi - lo) / 2;
    Node* root = new Node(sorted[mid]);
    root->left = buildBalanced(sorted, lo, mid - 1);
    root->right = buildBalanced(sorted, mid + 1, hi);
    return root;
}

void inorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    inorder(root->left);
    cout << root->key << ' ';
    inorder(root->right);
}

void preorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    cout << root->key << ' ';
    preorder(root->left);
    preorder(root->right);
}

void destroy(Node* root) {
    if (root == nullptr) {
        return;
    }
    destroy(root->left);
    destroy(root->right);
    delete root;
}

Node* buildExample() {
    Node* root = nullptr;
    for (int key : {50, 30, 70, 20, 40, 60, 80, 65}) {
        root = insert(root, key);
    }
    return root;
}

void showDelete(int key, const char* label) {
    Node* root = deleteNode(buildExample(), key);
    cout << "Delete " << key << " (" << label << "): root = " << root->key << ", inorder = ";
    inorder(root);
    cout << '\n';
    destroy(root);
}

int main() {
    Node* root = buildExample();
    cout << "Inorder: ";
    inorder(root);
    cout << '\n';

    cout << "Search 65: " << (search(root, 65) ? "found" : "not found") << '\n';
    cout << "Search 55: " << (searchIterative(root, 55) ? "found" : "not found") << '\n';
    cout << "Min = " << findMin(root)->key << ", Max = " << findMax(root)->key << '\n';
    cout << "Height = " << height(root) << '\n';
    cout << "Predecessor(50) = " << predecessor(root, 50)->key
         << ", Successor(50) = " << successor(root, 50)->key
         << ", Successor(65) = " << successor(root, 65)->key << '\n';
    cout << "Is BST: " << (isBST(root, LLONG_MIN, LLONG_MAX) ? "yes" : "no") << '\n';

    showDelete(20, "leaf");
    showDelete(60, "one child");
    showDelete(50, "two children");

    // Same keys, iterative insert: identical tree.
    Node* again = nullptr;
    for (int key : {50, 30, 70, 20, 40, 60, 80, 65}) {
        again = insertIterative(again, key);
    }
    cout << "Iterative insert preorder: ";
    preorder(again);
    cout << '\n';

    // A tree that breaks the BST rule deep down: 6 sits in 10's right subtree.
    Node* bad = new Node(10);
    bad->left = new Node(5);
    bad->right = new Node(15);
    bad->right->left = new Node(6);
    bad->right->right = new Node(20);
    cout << "Is the 10/5/15/6/20 tree a BST: " << (isBST(bad, LLONG_MIN, LLONG_MAX) ? "yes" : "no") << '\n';

    vector<int> sorted = {1, 2, 3, 4, 5, 6, 7};
    Node* balanced = buildBalanced(sorted, 0, (int)sorted.size() - 1);
    Node* skewed = nullptr;
    for (int key : sorted) {
        skewed = insert(skewed, key);
    }
    cout << "Balanced from sorted array: height = " << height(balanced) << ", preorder = ";
    preorder(balanced);
    cout << '\n';
    cout << "Inserting 1..7 in order: height = " << height(skewed) << '\n';

    for (Node* t : {root, again, bad, balanced, skewed}) {
        destroy(t);
    }
}
```

**Output:**

```text
Inorder: 20 30 40 50 60 65 70 80
Search 65: found
Search 55: not found
Min = 20, Max = 80
Height = 3
Predecessor(50) = 40, Successor(50) = 60, Successor(65) = 70
Is BST: yes
Delete 20 (leaf): root = 50, inorder = 30 40 50 60 65 70 80
Delete 60 (one child): root = 50, inorder = 20 30 40 50 65 70 80
Delete 50 (two children): root = 60, inorder = 20 30 40 60 65 70 80
Iterative insert preorder: 50 30 20 40 70 60 65 80
Is the 10/5/15/6/20 tree a BST: no
Balanced from sorted array: height = 2, preorder = 4 2 1 3 6 5 7
Inserting 1..7 in order: height = 6
```

The program was compiled with `-Wall -Wextra` and run under AddressSanitizer, which reports no leaks or invalid memory accesses.

## Recursive vs Iterative Implementation

| | Recursive | Iterative |
| --- | --- | --- |
| Code | Shorter, mirrors the definition | Slightly longer (insert needs a `parent` pointer) |
| Extra space | $O(h)$ call stack | $O(1)$ |
| Risk | Stack overflow on very deep (skewed) trees | None from depth |
| Best for | Delete, validate, build, exams | Search, insert, min/max in production code |

Both visit the same nodes in the same order, so their time complexity is identical.

## Time and Space Complexity

| Operation | Average (random inserts) | Worst case (skewed) | Balanced BST (AVL / red-black) |
| --- | --- | --- | --- |
| Search | $O(\log n)$ | $O(n)$ | $O(\log n)$ |
| Insert | $O(\log n)$ | $O(n)$ | $O(\log n)$ |
| Delete | $O(\log n)$ | $O(n)$ | $O(\log n)$ |
| Min / max | $O(\log n)$ | $O(n)$ | $O(\log n)$ |
| Inorder traversal | $O(n)$ | $O(n)$ | $O(n)$ |
| Height / validate | $O(n)$ | $O(n)$ | $O(n)$ |

All single-key operations are really $O(h)$. Space for the tree itself is $O(n)$; recursive operations add $O(h)$ stack space.

## Balanced vs Unbalanced BST

<Diagram
  src="binary-search-tree-bst/balanced-vs-skewed-bst"
  alt="Two BSTs with the keys 1 to 7. Left: inserted in the order 4, 2, 6, 1, 3, 5, 7 gives a perfect tree of height 2. Right: inserted in sorted order gives a right-leaning chain of height 6."
/>

The same seven keys produce a height-2 tree or a height-6 chain depending only on **insertion order**. Sorted (or nearly sorted) input is common in real data, so a plain BST can quietly turn into a linked list with $O(n)$ operations.

**Self-balancing BSTs** fix this by restructuring the tree with **rotations** after inserts and deletes:

- **AVL tree:** keeps the height difference at every node at most 1. Very fast lookups.
- **Red-black tree:** looser balance, fewer rotations on updates. This is what `std::map` and `std::set` use in the major standard libraries (libstdc++, libc++, MSVC).

In C++ you rarely write your own BST for production. Use `std::set` / `std::map`, which guarantee $O(\log n)$ search, insert and delete. Write your own to learn, and for exams and interviews.

## Real-World Applications

- **Ordered sets and maps**: `std::set`, `std::map`, Java's `TreeMap`.
- **Range queries**: "all keys between 30 and 65" is easy because subtrees are ordered.
- **Database and file-system indexes**: B-trees and B+ trees generalise the BST idea to many keys per node.
- **Schedulers**: Linux's Completely Fair Scheduler keeps runnable tasks in a red-black tree ordered by virtual runtime.
- **Autocomplete, leaderboards, event queues** where you need sorted order plus fast updates.

## Common Implementation Mistakes

1. **Not reconnecting the returned pointer.** Writing `insert(root->left, key);` instead of `root->left = insert(root->left, key);` creates the node and then loses it.
2. **Forgetting `root = insert(root, key)` in `main`.** The first insert into an empty tree returns the new root; ignoring it leaves `root == nullptr`.
3. **Validating with only parent–child comparisons.** See the "Is the 10/5/15/6/20 tree a BST" line in the output above.
4. **Wrong successor in case 3.** The successor is the minimum of the **right** subtree, not simply the right child.
5. **Deleting the successor node directly** instead of deleting its key from the right subtree. If the successor has a right child, that child gets lost.
6. **Using `<=` and `>=` inconsistently**, so duplicates end up on both sides and search misses them.
7. **Inserting sorted data into a plain BST** and expecting $O(\log n)$.
8. **Memory leaks:** every `new Node` needs a matching `delete`. Free the tree in postorder.

## Practice Problems

| Problem | Concept |
| --- | --- |
| [Search in a BST (LeetCode 700)](https://leetcode.com/problems/search-in-a-binary-search-tree/) | Search |
| [Insert into a BST (LeetCode 701)](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | Insert |
| [Delete Node in a BST (LeetCode 450)](https://leetcode.com/problems/delete-node-in-a-bst/) | All three deletion cases |
| [Validate BST (LeetCode 98)](https://leetcode.com/problems/validate-binary-search-tree/) | Range checking |
| [Convert Sorted Array to BST (LeetCode 108)](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | Balanced build |
| [Kth Smallest Element in a BST (LeetCode 230)](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | Inorder = sorted |

Paper exercises on our example tree:

1. Insert 35 and 75. Where do they go? (35 < 50 → 30; 35 > 30 → 40; 35 < 40 → **left child of 40**. 75 > 50 → 70; 75 > 70 → 80; 75 < 80 → **left child of 80**.)
2. Delete 70 from the original tree using the successor method. (Successor of 70 is 80; 80 is a leaf. Result: 50's right child holds 80, with 60 → 65 on its left.)
3. Delete 70 using the **predecessor** instead. (Predecessor is 65, the maximum of the left subtree; 60 keeps no right child; 65 becomes 50's right child with children 60 and 80.)

## Frequently Asked Questions

### Can a BST have duplicate keys?

The textbook definition uses strict inequalities, so no. In practice you choose a policy: ignore duplicates, send them consistently to one side, or keep a counter in the node. `std::multiset` allows duplicates.

### Why is BST search O(log n) only on average?

Search is $O(h)$. A BST built from random insertions has expected height $O(\log n)$, but adversarial or sorted input can make $h = n - 1$. Self-balancing trees make $O(\log n)$ a guarantee.

### Successor or predecessor for deletion: which is correct?

Both are correct and produce valid BSTs, just different shapes. Use whichever your course or the question specifies; the successor is the more common default.

### Is a heap a BST?

No. A binary heap orders parent against children only (parent ≤ children in a min-heap) and must be a complete tree. It cannot search for an arbitrary key in $O(\log n)$. More on this in the [tree interview questions](/posts/tree-interview-questions/).

## Next Steps

1. **Next:** [Most Common Tree Interview Questions](/posts/tree-interview-questions/) to practise recursion on binary trees.
2. Then [BST Interview Questions](/posts/bst-interview-questions/): kth smallest, LCA, recover BST and more.
3. For exams: [BST Questions for University Exams in Bangladesh](/posts/bst-questions-university-exams-bangladesh/).
