A Binary Search Tree, Drawn

2026-10-03  |  algorithms data structures diagrams

> TRANSMISSION: BST

DATE.......... 2026-10-03
TOPIC......... binary search trees
RENDER........ mermaid → svg, at build time
STATUS........ ONLINE

Seven nodes. Every node’s left subtree holds smaller values, every right subtree holds larger ones. That single invariant is the whole data structure.

LRLRLR50307020406080
A BST of range 20 - 80, step 10. Left of each node is smaller, right is larger.

Insert

Start at the root. 30 < 50, go left. 30 > 20… keep comparing until you hit an empty slot and hang the new node there.

insert(root, v):
  if root == null: return node(v)
  if v < root.value: root.left  = insert(root.left,  v)
  else:              root.right = insert(root.right, v)
  return root

The same walk, but you stop early when you find the value.

  • Balanced (what the diagram shows): ~log₂(n) comparisons. Seven nodes, at most three hops.
  • Sorted input, no rebalancing: the tree degenerates into a linked list, and lookup degrades to O(n).

That last point is why AVL trees and red-black trees exist — they rotate the tree back into shape after every insert.


Diagram source lives at assets/diagrams/bst.mmd, rendered to SVG with bb diagrams.

LRLRLR50307020406080
A BST of 20-80. Left of each node is smaller, right is larger.