AlgoViz

Binary search tree

medium 18 min

A binary search tree keeps every key in order: for each node, all keys in its left subtree are smaller and all keys in its right subtree are larger.

Video lesson · Chapter 1 of 6

A word opens one door

0:00 / 4:37

Binary search trees — The turning vault

1:01Reel

Read caption

A scarab courier routes key sixty through a search-tree vault. The route exposes the ancestor constraint and the effect of height on search. Smaller goes left. Larger goes right. Every turn keeps every earlier promise.

How it works

Step through the idea, or press Play.

Step 1 of 3

Compare at the node. Equal means found; smaller means the key can only be in the left subtree, larger only in the right

Understand it

Start here

What a binary search tree is

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. Think of a phone book: open it in the middle, and if the name you want comes earlier, you only ever look in the first half again.

A small BST

Everything left of 8 is smaller (1, 3, 6), everything right is larger (9, 10, 14). The same holds at 3 and at 10.
  • Left is less

    Every key in a node's left subtree is smaller than the node.

  • Right is more

    Every key in a node's right subtree is larger than the node.

  • Every subtree is a BST

    The rule holds at every node, so each subtree is a smaller BST. That is why the code is naturally recursive.

The invariant

The rule is about whole subtrees

The BST property

∀ v:x<v.key<yfor every x∈left(v) and every y∈right(v)\forall\, v:\quad x < v.\text{key} < y \quad \text{for every } x \in \text{left}(v) \text{ and every } y \in \text{right}(v)
Not just the two children: every descendant on each side. Each node is the pivot between two ranges.

Operation 1

Search: one comparison per level

Searching for a target

Each pass goes one level down and discards the other subtree, so a search makes at most hh comparisons.

In the tree above, searching for 6: at 8, 6<86 < 8, go left; at 3, 6>36 > 3, go right; at 6, found. 3 comparisons instead of checking all 7 nodes. Searching for 7 would go 8, 3, 6, then fall off at 6.right and return None.

Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef search(root, target):                 # recursive: O(h) stack    if root is None or root.val == target:        return root    if target < root.val:        return search(root.left, target)    return search(root.right, target)def search_iter(root, target):            # iterative: O(1) space    node = root    while node and node.val != target:        node = node.left if target < node.val else node.right    return noderoot = TreeNode(8, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(10, TreeNode(9), TreeNode(14)))print(search(root, 6).val, search_iter(root, 7))   # 6 None
Search, recursive and iterative. The loop version uses O(1) extra space.
Edit and run it in your browser

Operation 2

Insert: search, then fill the empty slot

Inserting a value

Insert is a search that does not give up: when it falls off the tree, the empty slot it reached is where the value belongs.
Tree (insertion order)InsertPathLands as
50, 30, 70, 20, 403550 → 30 → 40left child of 40
50, 25, 75, 12, 37, 625550 → 75 → 62left child of 62
50, 25, 75, 879050 → 75 → 87right child of 87
8, 3, 10, 1, 6, 9, 1478 → 3 → 6right child of 6
Every insert walks one path and adds one leaf. The number of comparisons is the depth of the new node.

Operation 3

Delete: three cases

Which delete case applies

The successor has no left child, so the final delete is always case 1 or case 2.
  • L: Leaf

    No children to worry about. The parent's pointer becomes None.

  • O: One child

    Lift the only child, with its whole subtree, into the node's place. Everything there was already on the correct side of the parent.

  • T: Two children

    Replace the value with the inorder successor (smallest key in the right subtree), then delete that successor below.

Worked example

Delete in code

Deleting 20, 30 and 50 from 50, 30, 70, 20, 40, 35, 60, 80, 65

  1. 1

    Delete 20: leaf

    Path 50 → 30 → 20. No children, so 30.left becomes None.

  2. 2

    Delete 30: one child

    30 now has only a right child, 40 (with 35 below). That subtree moves up to be 50's left child.

  3. 3

    Delete 50: two children

    Right once to 70, left to 60, which has no left child: the successor is 60. Write 60 into the root.

  4. 4

    Remove the old 60

    60 has only a right child, 65, so case 2 lifts 65 into its place. Inorder is now 35, 40, 60, 65, 70, 80.

Python
class TreeNode:    def __init__(self, val):        self.val, self.left, self.right = val, None, Nonedef insert(root, val):    if root is None:        return TreeNode(val)    if val < root.val:        root.left = insert(root.left, val)    elif val > root.val:        root.right = insert(root.right, val)    return rootdef delete(root, val):    if root is None:        return None    if val < root.val:        root.left = delete(root.left, val)    elif val > root.val:        root.right = delete(root.right, val)    else:        if root.left is None:          # leaf or only a right child            return root.right        if root.right is None:         # only a left child            return root.left        succ = root.right              # two children        while succ.left:            succ = succ.left        root.val = succ.val        root.right = delete(root.right, succ.val)    return rootdef inorder(node):    return inorder(node.left) + [node.val] + inorder(node.right) if node else []root = Nonefor k in [50, 30, 70, 20, 40, 35, 60, 80, 65]:    root = insert(root, k)for k in [20, 30, 50]:    root = delete(root, k)    print("after deleting", k, inorder(root))print("new root:", root.val)   # 60
Insert, delete and inorder together. Note that every call stores the returned root.
Edit and run it in your browser

Traversal

Inorder gives sorted order

An inorder traversal visits the left subtree, then the node, then the right subtree. On a BST that is exactly ascending order, in O(n)O(n) time and O(h)O(h) stack, with no comparisons at all. Preorder and postorder are the other two depth-first orders, covered in Tree DFS.

Why inorder is sorted

This holds at every node, so the whole output is in order. Proof by induction on the subtree size.
Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef kth_smallest(root, k):    stack, node = [], root    while stack or node:        while node:                  # slide down the left spine            stack.append(node)            node = node.left        node = stack.pop()           # next key in sorted order        k -= 1        if k == 0:            return node.val        node = node.rightroot = TreeNode(50, TreeNode(30, TreeNode(20), TreeNode(40)), TreeNode(70, TreeNode(60), TreeNode(80)))print([kth_smallest(root, k) for k in range(1, 8)])   # [20, 30, 40, 50, 60, 70, 80]
Kth smallest: an inorder walk that stops after k nodes. O(h + k) time.
Edit and run it in your browser

Checking

Validating a BST

Validate with bounds

Start with (−∞,+∞)(-\infty, +\infty). Going left tightens the upper bound, going right tightens the lower bound; the other bound is inherited from above.
Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef valid_bounds(node, low=float("-inf"), high=float("inf")):    if node is None:        return True    if not (low < node.val < high):        return False    return valid_bounds(node.left, low, node.val) and valid_bounds(node.right, node.val, high)def valid_inorder(root):    prev, stack, node = float("-inf"), [], root    while stack or node:        while node:            stack.append(node)            node = node.left        node = stack.pop()        if node.val <= prev:            return False        prev, node = node.val, node.right    return Truegood = TreeNode(50, TreeNode(30, TreeNode(20), TreeNode(40)), TreeNode(70))trap = TreeNode(50, TreeNode(30, TreeNode(20), TreeNode(55)), TreeNode(70))print(valid_bounds(good), valid_bounds(trap), valid_inorder(trap))   # True False False
Two correct O(n) checks: bounds, and a strictly increasing inorder sequence.
Edit and run it in your browser

Pass bounds down

  • Each node knows the full range its ancestors allow.
  • Catches 55 hiding under 30 in 50's left subtree.
  • O(n)O(n) time, O(h)O(h) stack.

Compare with children only

  • Checks left < node < right one level at a time.
  • Says the trap tree is valid.
  • The single most common BST interview bug.

Complexity

Everything costs O(h)

One path per operation

Tsearch=Tinsert=Tdelete=O(h),⌊log⁡2n⌋+1  ≤  h  ≤  nT_{\text{search}} = T_{\text{insert}} = T_{\text{delete}} = O(h), \qquad \lfloor \log_2 n \rfloor + 1 \;\le\; h \;\le\; n
Search, insert, delete, min and max each walk at most one root-to-leaf path. The height hh (counted in nodes) decides everything.

The best case: a balanced tree

n≤1+2+4+⋯+2h−1=2h−1  ⟹  h≥log⁡2(n+1)  ⟹  h=Θ(log⁡n) when balancedn \le 1 + 2 + 4 + \dots + 2^{h-1} = 2^{h} - 1 \;\Longrightarrow\; h \ge \log_2(n+1) \;\Longrightarrow\; h = \Theta(\log n) \text{ when balanced}
Level ii holds at most 2i2^i nodes. A million keys fit in about 20 levels, so about 20 comparisons.

The worst case: a chain

h=n  ⟹  O(n) per operation,building it: ∑i=0n−1i=n(n−1)2=O(n2)h = n \;\Longrightarrow\; O(n) \text{ per operation}, \qquad \text{building it: } \sum_{i=0}^{n-1} i = \frac{n(n-1)}{2} = O(n^2)
Inserting sorted keys puts each one at the bottom of a growing chain. Random insertion order gives an expected height of O(log⁡n)O(\log n) (about 2.99log⁡2n2.99 \log_2 n), but you rarely control the order.
OperationBalancedSkewedSpace
SearchO(log⁡n)O(\log n)O(n)O(n)O(1)O(1) iterative, O(h)O(h) recursive
InsertO(log⁡n)O(\log n)O(n)O(n)O(h)O(h) recursive
Delete (3 cases)O(log⁡n)O(\log n)O(n)O(n)O(h)O(h) recursive
Find min / maxO(log⁡n)O(\log n)O(n)O(n)O(1)O(1)
Inorder traversalO(n)O(n)O(n)O(n)O(h)O(h)
ValidateO(n)O(n)O(n)O(n)O(h)O(h)
hh = height. Balanced means h=O(log⁡n)h = O(\log n); skewed means h=nh = n, like a linked list. The tree itself takes O(n)O(n) space.

Balance

Balanced vs degenerate trees

Insert 10, 20, 30, 40, 50 in sorted order

Every key is the largest so far, so it always goes right. The tree is a linked list: finding 50 takes 5 comparisons. Insert 30, 20, 40, 10, 50 instead and the height is 3.

Balanced (bushy)

  • Height about log⁡2n\log_2 n.
  • Search, insert, delete in O(log⁡n)O(\log n).
  • Comes from random or middle-first insertion, or from a self-balancing tree.

Degenerate (skewed)

  • Height nn: a linked list with extra pointers.
  • Every operation O(n)O(n); recursion can hit Python's limit.
  • Comes from sorted or reverse-sorted insertion.
  • AVL tree

    Keeps the two subtree heights of every node within 1 of each other, using rotations after insert and delete. Strictly balanced, fast lookups.

  • Red-black tree

    Colours nodes red or black and limits the longest path to twice the shortest. Fewer rotations; used by Java's TreeMap and C++'s std::map.

  • B-tree

    Many keys per node and very shallow. The index structure inside most databases and file systems.

Choosing

BST or hash table?

NeedBalanced BSTHash table
Search / insert / deleteO(log⁡n)O(\log n)O(1)O(1) average
Keys in sorted orderO(n)O(n) inorderSort first: O(nlog⁡n)O(n \log n)
Min / maxO(log⁡n)O(\log n)O(n)O(n)
Range query [a, b]O(log⁡n+k)O(\log n + k)O(n)O(n)
Predecessor / successorO(log⁡n)O(\log n)O(n)O(n)
SpaceO(n)O(n)O(n)O(n)
kk is the number of keys reported. A plain BST matches these only while it stays balanced.

Use a BST when you need order

  • Sorted iteration, min and max.
  • Range queries: every key between aa and bb.
  • Floor, ceiling, predecessor and successor.

Use a hash table when you only look up

  • Only membership, insert and delete.
  • No sorted output or range queries needed.
  • Then O(1)O(1) average beats O(log⁡n)O(\log n).

Recap

Key takeaways

Key points

  • For every node: all left descendants are smaller, all right descendants are larger. Every subtree is a BST.
  • Search, insert and delete walk one root-to-leaf path: O(h).
  • h is about log₂ n when balanced and n when skewed; sorted insertion builds a chain.
  • Insert adds a leaf at the empty slot the search reaches; always keep the returned root.
  • Delete: Leaf (remove), One child (lift it), Two children (copy the inorder successor, then delete it).
  • Inorder successor: right once, then left all the way. It never has a left child.
  • Inorder traversal of a BST is sorted, in O(n).
  • Validate with min and max bounds or a strictly increasing inorder, never by checking children only.
  • AVL and red-black trees rebalance with rotations to guarantee O(log n).

Sources