Essential Data Structures home

Binary Search Tree

An ordered tree where every left child is smaller and every right child is larger, so a search walks down one path instead of scanning everything.

8 3 10 1 6 14 Smaller values go left, larger values go right, at every node.
Illustration: a binary search tree holding 1, 3, 6, 8, 10, and 14. Read it in order and the values come out sorted.

What it is

A binary search tree, or BST, is a tree where each node holds one value and has at most two children, left and right. The rule that makes it a search tree is simple: every value in the left subtree is smaller than the node's value, and every value in the right subtree is larger. The rule holds at every node, not just at the root, so the whole tree is ordered from top to bottom.

That ordering is what makes the tree useful. To find a value, you start at the root and compare. If the value you want is smaller, you go left. If it is larger, you go right. If it matches, you have found it. Each step throws away half of the remaining tree, at least when the tree is reasonably balanced, so a search touches only a path from the root down to a leaf.

Walking the tree in order, left subtree, then node, then right subtree, visits every value in sorted order. That is the in-order traversal, and it is the BST's party trick: a structure built for fast searching gives you sorted output for free.

How it works

Insert follows the same path as search. Start at the root, compare, go left for smaller and right for larger, until you reach an empty spot, and put the new node there. Delete is the one operation with a wrinkle. Removing a leaf is easy, and removing a node with one child means linking the child in its place. Removing a node with two children needs a replacement, usually the smallest value in the right subtree (the successor), which is then copied up and deleted from its old spot.

The catch is balance. If values arrive in sorted order, each insert goes to the far right, and the tree degenerates into a linked list: tall and thin, with every operation as slow as a scan. Random insertion order keeps the tree roughly balanced and fast, but a BST on its own makes no promises. Keeping the height small on purpose is what the self-balancing trees do, the AVL tree and the red-black tree, which rebalance as they go.

Finding the smallest value means walking left until there is no left child. Finding the largest means walking right. Finding the successor or predecessor of a value is the same idea, one step sideways and then as far as possible in the other direction. All of these cost one root-to-leaf walk.

Complexity

OperationAverageWorst case
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Minimum / maximumO(log n)O(n)
In-order traversalO(n)O(n)

The average column assumes the tree stays reasonably balanced, which happens when values arrive in a mixed order. The worst case is a degenerate tree, a straight line, which happens when values arrive in sorted order. A balanced BST keeps the height at O(log n), which is why self-balancing trees exist.

When to use it, and when not to

Use a binary search tree when you need ordered data with fast lookup: a set of values you search often, a map from keys to values where the keys should stay sorted, or a range query such as "all values between 10 and 20". If you need the smallest or largest value, or the values in sorted order, a BST hands them to you directly.

Do not use a plain BST when the insertion order is sorted or nearly sorted, because the tree will degenerate and lose its speed; use a self-balancing tree instead. Do not use it when you only need fast lookup by key and do not care about order, because a hash table is faster there, with O(1) average lookup and no ordering cost. Python's built-in dict and set are hash tables, not trees.

Where you meet it

Binary search trees are the idea behind ordered maps and sets in many languages. Java's TreeMap and C++'s std::map are red-black trees, a self-balancing kind of BST. Database indexes use the same ordering idea, in the wider B-tree form, so range queries stay fast. File systems, symbol tables in compilers, and any program that needs "find this key, and also give me the next one" are built on this shape.

In Python

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def insert(node, value):
    if node is None:
        return Node(value)
    if value < node.value:
        node.left = insert(node.left, value)
    elif value > node.value:
        node.right = insert(node.right, value)
    return node

def search(node, value):
    if node is None or node.value == value:
        return node
    if value < node.value:
        return search(node.left, value)
    return search(node.right, value)

def inorder(node, out):
    if node is not None:
        inorder(node.left, out)
        out.append(node.value)
        inorder(node.right, out)

root = None
for v in [8, 3, 10, 1, 6, 14]:
    root = insert(root, v)

found = search(root, 6)
print(found.value)          # 6

out = []
inorder(root, out)
print(out)                  # [1, 3, 6, 8, 10, 14]

In short: a binary search tree keeps values ordered by a simple rule, smaller left, larger right, so search, insert, and delete each walk one root-to-leaf path. The catch is balance: a tree fed sorted values becomes a slow line, which is why self-balancing trees exist.

Sources

← Home