Trees

BST insert · source
1function insert(root: Node | null, v: number): Node {
2 if (root === null) return new Node(v);
3 if (v < root.val) {
4 root.left = insert(root.left, v);
5 } else if (v > root.val) {
6 root.right = insert(root.right, v);
7 }
8 return root; // duplicates: ignored
9}
BST insert · liveEvery comparison sends you left or right — the shape is the history.
to insert42256713315488976

Insert 9 values, in arrival order. The first becomes the root.

1 / 27

How bst insert works

A binary search tree keeps one promise everywhere: everything in a node's left subtree is smaller, everything right is larger. Insertion just follows the promise — compare, go left or right, repeat until you fall off the tree, and that hole is where the new node belongs. No rebalancing, no shifting: one node pointer changes.

The tree's shape is the insertion history. Values arriving in shuffled order build a bushy tree of height ≈ log n; the same values arriving sorted build a chain — every insert goes right, and the “tree” degenerates into a linked list with O(n) operations. Watch it happen: set the values yourself in increasing order and the tree falls over sideways.

That degenerate case is why balanced trees exist (AVL, red-black) — same invariant, plus rotations that cap the height at O(log n). In interviews you rarely implement rotations, but you are expected to know why the worst case is O(n) and what fixes it. Note the duplicate policy too: this version ignores them; alternatives count occurrences or lean right — say which you chose.

space play / pause · ←→ step

Complexity

averageO(log n)
worstO(n)
spaceO(h) recursion
invariantleft < node < right