Binary Search Trees
How a binary search tree stores sorted data, how search, insert and delete work, why the shape matters, and what interviewers ask about it.
On this page
A binary search tree (BST) is a binary tree that keeps its values in order, so you can search, insert and delete in time proportional to the height of the tree. Use one when you need a collection that stays sorted while values are added and removed, and you also want to ask questions such as "what is the next larger value".
A sorted array can be searched quickly with binary search, but inserting into it means shifting every later element one place, which takes O(n). A BST finds the right position by following a single path and adds the value without moving any other node.
The ordering rule
Every node in a BST follows one rule: all values in its left subtree are smaller than the node's value, and all values in its right subtree are larger. This must hold for the whole subtree, not only for the direct children.
Because of this rule, one comparison at a node rules out one of its two sides. This is the same idea as binary search, built into the shape of the tree instead of into array indexes. The rule also means that an inorder traversal, which visits left subtree, node, then right subtree, produces the values in sorted order.
Search and insert
To search, start at the root and compare the target with the current node. If they are equal, you have found it. If the target is smaller, move to the left child, and if it is larger, move to the right child. If you reach an empty child, the value is not in the tree.
Insert uses the same walk. When you reach an empty child, that is the position where the new value belongs, and you attach a new node there. No existing node moves. The smallest value in the tree is the leftmost node and the largest is the rightmost node.
insert(node, val): if node is empty: return new node(val) if val < node.val: node.left = insert(node.left, val) if val > node.val: node.right = insert(node.right, val) return node- val
- 35
- comparisons
- 1
1At the root, 40, the value 35 is smaller, so the search goes left and the whole right side is ruled out.
- val
- 35
- comparisons
- 2
2At 20, the value 35 is bigger, so it goes right, and 10 is ruled out too.
- val
- 35
- comparisons
- 3
3At 30, the value 35 is bigger again, so it goes right.
- val
- 35
- comparisons
- 3
430 has no right child, so 35 goes in this empty spot. It is bigger than 30 and smaller than 40, so the rule still holds.
- comparisons
- 3
- nodes
- 8
5The insert took 3 comparisons, one for each node on the path. A search for 33 would walk the same path, step left from 35 onto an empty child, and report that 33 is not in the tree.
// TreeNode is the same class as in Binary Trees.
function contains(node, val) {
while (node !== null) {
if (val === node.val) return true;
node = val < node.val ? node.left : node.right; // throw away one side
}
return false;
}
// Returns the root of the tree with val added.
function insert(node, val) {
if (node === null) return new TreeNode(val); // found the empty spot
if (val < node.val) node.left = insert(node.left, val);
else if (val > node.val) node.right = insert(node.right, val);
return node; // a duplicate is ignored
}
let root = null;
for (const v of [40, 20, 60, 10, 30, 50, 70, 35]) root = insert(root, v);
contains(root, 35); // true
contains(root, 33); // false# TreeNode is the same class as in Binary Trees.
def contains(node, val):
while node is not None:
if val == node.val:
return True
node = node.left if val < node.val else node.right # throw away one side
return False
# Returns the root of the tree with val added.
def insert(node, val):
if node is None:
return TreeNode(val) # found the empty spot
if val < node.val:
node.left = insert(node.left, val)
elif val > node.val:
node.right = insert(node.right, val)
return node # a duplicate is ignored
root = None
for v in [40, 20, 60, 10, 30, 50, 70, 35]:
root = insert(root, v)
contains(root, 35) # True
contains(root, 33) # FalseThe insert function returns the root of the updated subtree, and the caller stores it with node.left = ... or node.right = .... This also handles inserting into an empty tree without a special case, because the returned new node simply becomes the root.
Delete
Delete is harder than insert because the tree must stay valid after the node is removed. First find the node, then handle one of three cases depending on how many children it has.
- No children. Remove the node.
- One child. Replace the node with its child. Everything under that child is already on the correct side of the removed node's parent.
- Two children. Find the successor, which is the next larger value and is the leftmost node of the right subtree. Copy the successor's value into the node, then delete the successor from the right subtree. The successor has no left child, so that second delete is one of the first two cases. Using the predecessor, the rightmost node of the left subtree, works equally well.
find the node with valif it has 0 or 1 child: replace it with that childelse: next = leftmost node of its right subtree copy next.val into the node delete next.val from the right subtree120 is smaller than 40, so the search goes left.
2The search finds 20. It has two children, so it cannot simply be cut out.
3To find the successor, step right to 30 and then go left as far as possible. 30 has no left child, so 30 is the successor.
4Copy 30 into the node that held 20. It fits there because it is bigger than the left child, 10, and smaller than everything else on the right, which is 35. For now 30 appears twice.
5Delete the old 30 from the right subtree. It has one child, 35, which moves up into its place.
6An inorder traversal now reads 10, 30, 35, 40, 50, 60, 70, which is sorted, so the tree is still a valid BST.
// Returns the root of the tree with val removed.
function remove(node, val) {
if (node === null) return null; // val is not in the tree
if (val < node.val) node.left = remove(node.left, val);
else if (val > node.val) node.right = remove(node.right, val);
else {
if (node.left === null) return node.right; // 0 or 1 child:
if (node.right === null) return node.left; // the child moves up
let next = node.right; // 2 children: find the
while (next.left !== null) next = next.left; // next bigger value
node.val = next.val; // copy it here
node.right = remove(node.right, next.val); // and remove the copy
}
return node;
}
root = remove(root, 20); // inorder: 10, 30, 35, 40, 50, 60, 70# Returns the root of the tree with val removed.
def remove(node, val):
if node is None:
return None # val is not in the tree
if val < node.val:
node.left = remove(node.left, val)
elif val > node.val:
node.right = remove(node.right, val)
else:
if node.left is None: # 0 or 1 child:
return node.right # the child moves up
if node.right is None:
return node.left
nxt = node.right # 2 children: find the
while nxt.left is not None: # next bigger value
nxt = nxt.left
node.val = nxt.val # copy it here
node.right = remove(node.right, nxt.val) # and remove the copy
return node
root = remove(root, 20) # inorder: 10, 30, 35, 40, 50, 60, 70Cost and tree shape
Search, insert and delete each follow one path from the root, so each costs O(h), where h is the height of the tree. In a well-shaped tree the height is about log₂ n, which is about 20 for a million values.
The height depends on the order in which values were inserted. If you insert 10, 20, 30, 40, 50 in that order, each value becomes the right child of the previous one, and the tree turns into a chain of height n, like the one described in Binary Trees. Searching that tree is no faster than scanning a linked list.
| Approach | Time | Space | Why |
|---|---|---|---|
| Sorted array | O(log n) search, O(n) insert | O(n) | Insert and delete shift the later elements over. |
| BST, balanced shape | O(log n) | O(n) | Search, insert and delete follow one path of about log₂ n nodes. |
| BST, worst shape | O(n) | O(n) | Inserting sorted values builds a chain, and the path is the whole tree. |
Variants
Self-balancing trees
A self-balancing BST, such as an AVL tree or a red-black tree, rearranges nodes with small local changes called rotations after each insert or delete, so the height stays O(log n) whatever the insert order. An AVL tree keeps the heights of every node's two subtrees within 1 of each other, so it is shallower and faster to search, but it rotates more often on updates. A red-black tree allows a looser balance, so it does fewer rotations on insert and delete, which is why most libraries choose it. This is what real libraries use: Java's TreeMap and C++'s std::map are balanced BSTs. In an interview you are rarely asked to code the rotations, but you are expected to know that a plain BST can degrade and that a balanced tree prevents it. See Balanced Trees.
Duplicate values
The code above ignores a value that is already in the tree, which is right when the tree represents a set. If you need to keep duplicates, either store a count in each node, or choose one side, for example always the right, and apply that choice consistently in insert, search and delete. Sending equal values to different sides inconsistently makes searches miss them.
When a BST is the wrong tool
If you only need to look up, insert and delete by exact key, a hash table does it in O(1) on average and is simpler. A BST is worth its O(log n) cost when you also need order: the smallest or largest key, the next key above a given one, all keys in a range, or all keys in sorted order. If you only ever need the smallest or most urgent item, a heap is simpler and faster still.
Pitfalls
In the interview
Think of a BST when the problem says the input is a binary search tree, or when it asks you to keep values sorted while they change, or to find the next larger or smaller value, a value in a range, or the k-th smallest value. If the problem gives you a BST, the ordering is a hint: use it to discard half of the tree at each step instead of visiting every node.
Questions to expect:
- "How do you check that a tree is a valid BST?" Do a traversal that carries a lower and an upper bound for each node, and fail if a value is outside its bounds. Checking only the parent is the common wrong answer. An inorder traversal that checks the values are strictly increasing also works.
- "What is the worst-case time of search, and when does it happen?" It is O(n), when the tree is a chain, which is what you get by inserting values that are already sorted. A self-balancing tree keeps the height at O(log n).
- "How do you find the k-th smallest value?" Run an inorder traversal and stop at the k-th value, which takes O(h + k). If the question is asked many times on a changing tree, store the size of each subtree in its node so you can descend directly in O(h).
- "How do you find the next larger value after a given value?" Walk down from the root. Each time you go left at a node, remember that node as a candidate, because it is larger than the target. When the walk ends, the last remembered candidate is the answer. If the target node has a right subtree, the answer is the leftmost node of that subtree. This takes O(h).
- "How do you list all values between a low and a high bound?" Do an inorder traversal that skips any subtree that cannot contain a value in the range: do not go left from a node that is already at or below the low bound, and do not go right from a node at or above the high bound. This takes O(h + k), where k is the number of values returned.
- "How do you find the lowest common ancestor of two nodes in a BST?" Start at the root. If both values are smaller than the current node, go left, and if both are larger, go right. The first node where they split, or where one of them equals the node, is the answer.
- "How do you build a balanced BST from a sorted array?" Make the middle element the root, then build the left subtree from the left half and the right subtree from the right half. This gives height about log₂ n.
- "Why use a BST instead of a hash table or a sorted array?" A hash table has no order, so it cannot give the next larger key or a range. A sorted array has O(n) inserts. A BST supports ordered queries and updates in O(log n) when it is balanced.
In the tree from the first trace (root 40, then 20 and 60, then 10, 30, 50, 70), where does 55 go?
You insert the values 1, 2, 3, ..., 1,000 into an empty BST in that order. About how many comparisons does a search for 1,000 take?
You delete a node with two children. Which value should replace it?
What to practise next
Continue with Balanced Trees to see how the height is kept small, or with Heaps and Priority Queues for when you only need the smallest or most urgent item.