Data Structures & Algorithms · Module 8 · Lesson 21 min read

Binary Search Trees

The BST rule

For every node: everything in the left subtree is smaller, and everything in the right subtree is larger.

Operations

OperationBalanced treeWorst (line-shaped)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
In-order traversalO(n), sorted outputO(n)

Search and insert

Start at the root: go left if the target is smaller, right if it's bigger, until you find it (or an empty spot to insert into).

Delete: three cases

  1. A leaf: just remove it.
  2. One child: replace the node with its child.
  3. Two children: replace its value with its in-order successor (the smallest node in the right subtree), then delete that successor.

Balance matters

Inserting already-sorted data creates a "linked list" tree, which is O(n). Self-balancing trees (AVL, red-black) rebalance automatically, keeping O(log n). They power Java's TreeMap, C++'s std::map, and database indexes (B-trees).

Classic interview questions

  • Validate a BST: pass down low < node.val < high bounds. Checking only the children is not enough.
  • Kth smallest: the kth item of an in-order traversal.
  • Lowest common ancestor: the first node where the two values split left and right.

Example

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

def insert(root, val):
    if root is None:
        return Node(val)
    if val < root.val:
        root.left = insert(root.left, val)
    else:
        root.right = insert(root.right, val)
    return root

def search(root, val):
    while root and root.val != val:
        root = root.left if val < root.val else root.right
    return root is not None

def inorder(root):
    return [] if not root else inorder(root.left) + [root.val] + inorder(root.right)

def is_valid_bst(node, low=float("-inf"), high=float("inf")):
    if node is None:
        return True
    if not low < node.val < high:
        return False
    return (is_valid_bst(node.left, low, node.val)
            and is_valid_bst(node.right, node.val, high))

root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, v)

print(inorder(root))                    # [20, 30, 40, 50, 60, 70, 80]
print(search(root, 60), search(root, 65))   # True False
print(is_valid_bst(root))               # True
print(inorder(root)[2])                 # 3rd smallest → 40