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 time, where is the height: when the tree is balanced, 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. Next: Tree Interview Questions. All parts: Trees & Graphs.
What Is a Binary Search Tree?
A Binary Search Tree (BST) is a type of binary tree 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:
50, 30, 70, 20, 40, 60, 80, 65
BST Properties
For every node x in a BST:
- Every key in
x’s left subtree is less thanx->key. - Every key in
x’s right subtree is greater thanx->key. - 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: | Follow one path: |
| 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:
- Output
Search Operation
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
nullptrproves the key is absent, because that is the only place it could have been.
// 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;
}
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.
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.
// 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:
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
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
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
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:
- Find the successor: go to 70, then left to 60. 60 has no left child, so it is the minimum.
- Copy 60 into the root.
- 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.
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.
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 .
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:
// 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 , because it needs every path:
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:
// 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 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. total, which is 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 :
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.
#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:
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 | call stack | |
| 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 | |||
| Insert | |||
| Delete | |||
| Min / max | |||
| Inorder traversal | |||
| Height / validate |
All single-key operations are really . Space for the tree itself is ; recursive operations add stack space.
Balanced vs Unbalanced BST
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 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::mapandstd::setuse 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 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’sTreeMap. - 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
- Not reconnecting the returned pointer. Writing
insert(root->left, key);instead ofroot->left = insert(root->left, key);creates the node and then loses it. - Forgetting
root = insert(root, key)inmain. The first insert into an empty tree returns the new root; ignoring it leavesroot == nullptr. - Validating with only parent–child comparisons. See the “Is the 10/5/15/6/20 tree a BST” line in the output above.
- Wrong successor in case 3. The successor is the minimum of the right subtree, not simply the right child.
- 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.
- Using
<=and>=inconsistently, so duplicates end up on both sides and search misses them. - Inserting sorted data into a plain BST and expecting .
- Memory leaks: every
new Nodeneeds a matchingdelete. Free the tree in postorder.
Practice Problems
| Problem | Concept |
|---|---|
| Search in a BST (LeetCode 700) | Search |
| Insert into a BST (LeetCode 701) | Insert |
| Delete Node in a BST (LeetCode 450) | All three deletion cases |
| Validate BST (LeetCode 98) | Range checking |
| Convert Sorted Array to BST (LeetCode 108) | Balanced build |
| Kth Smallest Element in a BST (LeetCode 230) | Inorder = sorted |
Paper exercises on our example tree:
- 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.)
- 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.)
- 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 . A BST built from random insertions has expected height , but adversarial or sorted input can make . Self-balancing trees make 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 . More on this in the tree interview questions.
Next Steps
- Next: Most Common Tree Interview Questions to practise recursion on binary trees.
- Then BST Interview Questions: kth smallest, LCA, recover BST and more.
- For exams: BST Questions for University Exams in Bangladesh.