intermediatedata-structures

Binary Search Tree

Binary Search Tree

A Binary Search Tree (BST) is a hierarchical data structure where each node has at most two children, and for every node: all values in its left subtree are smaller, and all values in its right subtree are larger. This ordering property enables efficient searching, insertion, and deletion in O(log n) average time — similar to binary search on a sorted array, but with the flexibility to insert and delete without shifting elements.

The BST Property

For every node with value v:

  • All nodes in the left subtree have values < v
  • All nodes in the right subtree have values > v

This invariant holds recursively for every subtree in the tree.

Core Operations

OperationAverageWorst (unbalanced)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Min/MaxO(log n)O(n)
In-order traversalO(n)O(n)

How It Works

  1. Start at the root
  2. If the target equals the current node, return it
  3. If the target is less, go left
  4. If the target is greater, go right
  5. If you reach a null node, the target doesn't exist

Insertion

  1. Search for where the value should go
  2. When you reach a null position, create a new node there

Deletion

Three cases:

  1. Leaf node: Simply remove it
  2. One child: Replace the node with its child
  3. Two children: Find the in-order successor (smallest in right subtree), copy its value, then delete the successor

Step-by-Step Example

Insert [8, 3, 10, 1, 6, 14, 4, 7]:

        8
       / \
      3   10
     / \    \
    1   6   14
       / \
      4   7

Search for 6: 8 → left → 3 → right → 6 ✓ (3 comparisons) Search for 5: 8 → left → 3 → right → 6 → left → 4 → right → null ✗ (not found)

Code Snippet

class TreeNode:
    """A single node in the binary search tree."""

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


class BinarySearchTree:
    """Binary Search Tree with search, insert, and delete operations."""

    def __init__(self):
        self.root = None

    def insert(self, value: int) -> None:
        """Insert a value into the BST."""
        self.root = self._insert_recursive(self.root, value)

    def _insert_recursive(self, node, value: int):
        if node is None:
            return TreeNode(value)
        if value < node.value:
            node.left = self._insert_recursive(node.left, value)
        elif value > node.value:
            node.right = self._insert_recursive(node.right, value)
        return node

    def search(self, value: int) -> bool:
        """Check if a value exists in the BST."""
        current = self.root
        while current is not None:
            if value == current.value:
                return True
            elif value < current.value:
                current = current.left
            else:
                current = current.right
        return False

    def delete(self, value: int) -> None:
        """Remove a value from the BST."""
        self.root = self._delete_recursive(self.root, value)

    def _delete_recursive(self, node, value: int):
        if node is None:
            return None

        if value < node.value:
            node.left = self._delete_recursive(node.left, value)
        elif value > node.value:
            node.right = self._delete_recursive(node.right, value)
        else:
            # Node found — handle three cases
            if node.left is None:
                return node.right
            if node.right is None:
                return node.left

            # Two children: find in-order successor
            successor = self._find_min(node.right)
            node.value = successor.value
            node.right = self._delete_recursive(node.right, successor.value)

        return node

    def _find_min(self, node):
        """Find the node with the minimum value in a subtree."""
        current = node
        while current.left is not None:
            current = current.left
        return current

    def inorder_traversal(self) -> list[int]:
        """Return all values in sorted order."""
        result = []
        self._inorder(self.root, result)
        return result

    def _inorder(self, node, result: list) -> None:
        if node is not None:
            self._inorder(node.left, result)
            result.append(node.value)
            self._inorder(node.right, result)

Complexity Analysis

Time Complexity: O(log n) average, O(n) worst case

  • In a balanced BST, the height is O(log n), so search/insert/delete traverse at most log n levels.
  • In the worst case (e.g., inserting sorted data: 1, 2, 3, 4, 5), the tree degenerates into a linked list with height n.

Space Complexity: O(n)

The tree stores n nodes, each with a value and two pointers. Recursive operations use O(h) stack space where h is the height.

Balanced vs. Unbalanced

InputTree shapeHeightOperations
RandomRoughly balancedO(log n)O(log n)
SortedLinked listO(n)O(n)
AlternatingNearly balancedO(log n)O(log n)

To guarantee O(log n) performance, use self-balancing variants:

  • AVL Tree: Strict balance (height difference ≤ 1)
  • Red-Black Tree: Relaxed balance (used in most standard libraries)
  • B-Tree: Used in databases and filesystems

Traversal Orders

OrderSequenceUse case
In-orderLeft → Root → RightSorted output
Pre-orderRoot → Left → RightCopy/serialize tree
Post-orderLeft → Right → RootDelete tree, evaluate expressions
Level-orderBFS by levelPrint tree layer by layer

When to Use BSTs

  • Dynamic sorted data: Need to insert, delete, and search while maintaining order.
  • Range queries: Find all elements between two values efficiently.
  • Ordered iteration: In-order traversal gives sorted output.
  • Floor/Ceiling queries: Find the largest value ≤ x or smallest value ≥ x.
  • Symbol tables with ordering: When you need both fast lookup and sorted access.

When to Avoid BSTs

  • Unordered lookups only: Hash maps are faster (O(1) vs O(log n)) if you don't need ordering.
  • Static data: A sorted array with binary search is simpler and uses less memory.
  • Guaranteed worst-case: Use a self-balancing variant rather than a plain BST.

Key Properties

PropertyValue
Average searchO(log n)
Worst-case searchO(n)
OrderedYes (in-order traversal)
DynamicYes (efficient insert/delete)
Balanced guaranteeNo (use AVL/Red-Black for this)