Skip to main content

Trees & BSTs

Learning objectives
  • Write pre/in/post/level-order traversals recursively and iteratively in Go without hesitation
  • Choose between "return information up" and "pass constraints down" recursion for a tree problem
  • Implement BST search, insert and delete, and explain why balancing is needed
  • Compare AVL, red-black and B+trees and explain why databases index with B+trees
  • Build a trie for prefix search and autocomplete, and know its memory cost

TL;DR​

  • Traversal order is the algorithm: in-order of a BST is sorted; pre-order serializes structure; post-order computes children before parents (heights, sizes); level-order (BFS) answers "per depth" questions.
  • Two recursion shapes: bottom-up (each call returns something about its subtree: height, max path) and top-down (pass bounds or accumulated state into children: BST validation, path sums).
  • BST operations are O(h) — O(log n) when balanced, O(n) when you insert sorted keys into a naive BST. Real systems use self-balancing trees.
  • Red-black trees (looser balance, cheap updates) dominate in-memory ordered maps; B+trees (hundreds of keys per page-sized node, linked leaves) dominate on-disk indexes because they minimize page reads.
  • Tries give O(L) prefix lookups independent of the number of keys — autocomplete, routers, longest-prefix match — at a high memory cost unless compressed (radix tree).
  • Go has no built-in ordered map: use a sorted slice + binary search for static data, or a B-tree package such as github.com/google/btree.

When to reach for it​

  • The input is a TreeNode, a hierarchy (org chart, category tree, chart of accounts), or nested data (JSON, ASTs).
  • "Sorted order with inserts and deletes", "k-th smallest", "floor/ceiling", "range query" → BST / ordered map.
  • "Per level", "right side view", "minimum depth" → BFS level-order.
  • "Path from root", "ancestor", "subtree property" → DFS.
  • "Prefix", "starts with", "autocomplete", "dictionary of words" → trie.
  • System design: "why is this query slow / how does the index work" → B+tree; "ordered leaderboard" → skip list or balanced tree.

Core concepts​

Vocabulary​

Depth is the distance from the root; height is the longest distance down to a leaf. A balanced tree keeps height O(log n). A complete tree fills every level except possibly the last, left to right — which is why heaps fit in an array. A BST keeps every key in the left subtree smaller and every key in the right subtree larger than the node's key — for the whole subtree, not just the direct children.

For this BST: pre-order 8 3 1 6 4 7 10 14 13, in-order 1 3 4 6 7 8 10 13 14 (sorted), post-order 1 4 7 6 3 13 14 10 8, level-order [8] [3 10] [1 6 14] [4 7 13].

Traversals​

type TreeNode struct {
Val int
Left, Right *TreeNode
}

func inorder(root *TreeNode) []int {
var out []int
var walk func(*TreeNode)
walk = func(n *TreeNode) {
if n == nil {
return
}
walk(n.Left)
out = append(out, n.Val) // move above walk(n.Left) for pre-order, below walk(n.Right) for post-order
walk(n.Right)
}
walk(root)
return out
}

Iterative versions replace the call stack with an explicit one — useful for very deep trees, for iterators that pause between elements (BST iterator, LeetCode 173), and because interviewers ask:

func inorderIterative(root *TreeNode) []int {
var out []int
var stack []*TreeNode
for curr := root; curr != nil || len(stack) > 0; {
for curr != nil { // go as far left as possible
stack = append(stack, curr)
curr = curr.Left
}
curr = stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, curr.Val)
curr = curr.Right
}
return out
}

func preorderIterative(root *TreeNode) []int {
if root == nil {
return nil
}
var out []int
stack := []*TreeNode{root}
for len(stack) > 0 {
n := stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, n.Val)
if n.Right != nil { // push right first so left is processed first
stack = append(stack, n.Right)
}
if n.Left != nil {
stack = append(stack, n.Left)
}
}
return out
}

// postorderIterative: a root-right-left traversal, reversed, is left-right-root.
func postorderIterative(root *TreeNode) []int {
if root == nil {
return nil
}
var out []int
stack := []*TreeNode{root}
for len(stack) > 0 {
n := stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, n.Val)
if n.Left != nil {
stack = append(stack, n.Left)
}
if n.Right != nil {
stack = append(stack, n.Right)
}
}
slices.Reverse(out)
return out
}

All traversals are O(n) time; recursive and stack-based versions use O(h) space, level-order uses O(w) for the widest level.

BST operations​

Search and insert follow one root-to-leaf path. Delete has three cases: a leaf (remove it), one child (splice the child up), two children (copy the in-order successor — the minimum of the right subtree — into the node, then delete the successor from the right subtree).

func searchBST(root *TreeNode, target int) *TreeNode {
for n := root; n != nil; {
switch {
case target < n.Val:
n = n.Left
case target > n.Val:
n = n.Right
default:
return n
}
}
return nil
}

func insertBST(root *TreeNode, v int) *TreeNode {
if root == nil {
return &TreeNode{Val: v}
}
if v < root.Val {
root.Left = insertBST(root.Left, v)
} else {
root.Right = insertBST(root.Right, v)
}
return root
}

// deleteBST removes key and returns the new subtree root (LeetCode 450).
func deleteBST(root *TreeNode, key int) *TreeNode {
if root == nil {
return nil
}
switch {
case key < root.Val:
root.Left = deleteBST(root.Left, key)
case key > root.Val:
root.Right = deleteBST(root.Right, key)
default:
if root.Left == nil { // zero or one child: splice
return root.Right
}
if root.Right == nil {
return root.Left
}
succ := root.Right // two children: use the in-order successor
for succ.Left != nil {
succ = succ.Left
}
root.Val = succ.Val
root.Right = deleteBST(root.Right, succ.Val)
}
return root
}

All three are O(h). Insert keys 1, 2, 3, …, n in order and the "tree" becomes a linked list with h = n — the reason production ordered maps rebalance.

Balanced trees: AVL, red-black, B-trees​

StructureBalance rule (simplified)HeightStrengthWhere you meet it
AVLSubtree heights differ by at most 1≈1.44 log₂ n worst caseShallowest → fastest lookupsRead-heavy in-memory sets
Red-blackNo red node has a red child; equal black count on every root-to-leaf path≤ 2 log₂(n + 1)At most a few rotations per updateJava TreeMap, typical C++ std::map, Linux kernel (scheduler, epoll, timers)
B-tree / B+treeEvery node (except root) at least half full; all leaves at the same depthlog base fan-out of n — 3–4 levels for billions of keysFew page reads; B+tree leaves linked for range scansPostgreSQL, MySQL InnoDB and SQLite indexes; many file systems
Skip listProbabilistic levelsExpected O(log n)Simple, lock-friendly, easy range iterationRedis sorted sets, LevelDB/RocksDB memtables

Both AVL and red-black trees restore balance with rotations — local O(1) pointer rewrites that change shape but preserve in-order order. You will rarely implement one in an interview; you are expected to know why they exist and their guarantees.

Why databases use B+trees, not binary trees. Disk and SSD reads happen in pages (8 KB in PostgreSQL, 16 KB in InnoDB by default). A binary tree of 1B keys is about 30 levels deep — up to 30 random page reads. A B+tree node fills a whole page with keys: with roughly 16-byte keys plus 8-byte child pointers, an internal node holds a few hundred entries (rough), so three levels address tens of millions of rows and four levels billions. Upper levels stay in the buffer cache, so a point lookup is typically one or two physical reads, and range scans (WHERE created_at BETWEEN …) walk the linked leaves sequentially.

See Indexing for composite and covering indexes and Storage Engines: B-Tree vs LSM for the write-path trade-off.

Tries​

A trie stores strings character by character; every path from the root spells a prefix, and a flag marks complete words. Lookup and insert cost O(L) for a word of length L — independent of how many words are stored.

Memory is the catch: a node with a [26]*node array costs about 208 bytes of pointers even when it has one child. Production variants compress single-child chains (radix / Patricia trees) — used by Go HTTP routers such as httprouter and chi, and by IP routing tables for longest-prefix match. For autocomplete at scale you also cache the top-k completions at each node (Search Autocomplete).

Trade-offs​

OptionStrengthsWeaknessesChoose when
Hash mapO(1) average point lookupsNo order, no range or prefix queriesExact-key lookups only
Sorted slice + binary searchCompact, cache-friendly, O(log n) lookup, range scansO(n) insert/deleteMostly static ordered data
Naive BSTSimpleO(n) worst case on sorted inputInterviews, randomized inputs
Red-black / AVL treeO(log n) guaranteed, ordered iterationPointer-heavy, complex codeIn-memory ordered maps with frequent updates
B-tree (in memory or on disk)High fan-out, cache/page friendly, orderedMore complex; overkill for tiny setsLarge ordered datasets, database indexes
Trie / radix treeO(L) prefix queriesMemory-hungry unless compressedAutocomplete, routing, prefix matching

In practice​

Problem 1 — Binary Tree Level Order Traversal (LeetCode 102)​

Problem. Return node values grouped by depth, top to bottom.

Approach. BFS with a queue; process exactly len(queue) nodes per round so each round is one level.

func levelOrder(root *TreeNode) [][]int {
if root == nil {
return nil
}
var levels [][]int
queue := []*TreeNode{root}
for len(queue) > 0 {
level := make([]int, 0, len(queue))
for range len(queue) { // the range expression is evaluated once: this level only
n := queue[0]
queue = queue[1:]
level = append(level, n.Val)
if n.Left != nil {
queue = append(queue, n.Left)
}
if n.Right != nil {
queue = append(queue, n.Right)
}
}
levels = append(levels, level)
}
return levels
}

Complexity. O(n) time, O(w) extra space for the widest level. Variants: right side view (last of each level), zigzag (reverse alternate levels), minimum depth (first leaf found).

Problem 2 — Validate Binary Search Tree (LeetCode 98)​

Problem. Decide whether a binary tree satisfies the BST property (strictly increasing in-order).

Approach. Top-down: pass the allowed open interval (lo, hi) into each subtree. Using the bounding nodes instead of sentinel integers avoids overflow bugs with math.MinInt/math.MaxInt values in the tree.

func isValidBST(root *TreeNode) bool {
var check func(n, lo, hi *TreeNode) bool
check = func(n, lo, hi *TreeNode) bool {
if n == nil {
return true
}
if (lo != nil && n.Val <= lo.Val) || (hi != nil && n.Val >= hi.Val) {
return false
}
return check(n.Left, lo, n) && check(n.Right, n, hi)
}
return check(root, nil, nil)
}

Complexity. O(n) time, O(h) space. Alternative: in-order traversal checking each value exceeds the previous one.

Problem 3 — Lowest Common Ancestor of a Binary Tree (LeetCode 236)​

Problem. Given two nodes p and q in a binary tree (not necessarily a BST), find their deepest common ancestor.

Approach. Bottom-up: each call returns p, q, their LCA, or nil for its subtree. If both sides return non-nil, the current node is where the paths split. For a BST (LeetCode 235) it is simpler: walk down from the root while both values are on the same side.

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
switch {
case left != nil && right != nil:
return root // p and q are in different subtrees
case left != nil:
return left
default:
return right
}
}

Complexity. O(n) time, O(h) space. It assumes both nodes exist; ask, because if not you must track whether each was actually found. Real-world shape: "nearest common parent category" in a product taxonomy, or the closest shared cost center in a chart of accounts.

Problem 4 — Implement Trie with autocomplete (LeetCode 208, extended)​

Problem. Support Insert, Search (whole word), StartsWith (prefix), and — the realistic extension — Complete(prefix, k) returning up to k words in lexicographic order.

Approach. Fixed [26]*Trie children for lowercase ASCII; DFS from the prefix node, visiting children in letter order, with a reusable byte buffer.

type Trie struct {
children [26]*Trie
word bool
}

func (t *Trie) Insert(w string) {
n := t
for i := 0; i < len(w); i++ {
c := w[i] - 'a'
if n.children[c] == nil {
n.children[c] = &Trie{}
}
n = n.children[c]
}
n.word = true
}

func (t *Trie) find(prefix string) *Trie {
n := t
for i := 0; i < len(prefix) && n != nil; i++ {
n = n.children[prefix[i]-'a']
}
return n
}

func (t *Trie) Search(w string) bool {
n := t.find(w)
return n != nil && n.word
}

func (t *Trie) StartsWith(prefix string) bool { return t.find(prefix) != nil }

// Complete returns up to k words that start with prefix, in lexicographic order.
func (t *Trie) Complete(prefix string, k int) []string {
start := t.find(prefix)
if start == nil {
return nil
}
var out []string
buf := []byte(prefix)
var dfs func(*Trie)
dfs = func(n *Trie) {
if len(out) == k {
return
}
if n.word {
out = append(out, string(buf))
}
for c, child := range n.children {
if child != nil {
buf = append(buf, byte('a'+c))
dfs(child)
buf = buf[:len(buf)-1]
}
}
}
dfs(start)
return out
}

Complexity. Insert/Search/StartsWith O(L). Complete is O(L + size of the visited subtree), stopping early after k results. Ranking by popularity instead of alphabet needs per-node top-k caches or a heap — see Heaps & Priority Queues.

Practice list​

  • Easy: Maximum Depth of Binary Tree (104), Invert Binary Tree (226), Same Tree (100), Diameter of Binary Tree (543), Subtree of Another Tree (572)
  • Medium: Binary Tree Level Order Traversal (102), Validate Binary Search Tree (98), Kth Smallest Element in a BST (230), Lowest Common Ancestor of a BST (235), Construct Binary Tree from Preorder and Inorder Traversal (105), Binary Tree Right Side View (199), Delete Node in a BST (450), Implement Trie (208)
  • Hard: Binary Tree Maximum Path Sum (124), Serialize and Deserialize Binary Tree (297), Word Search II (212)

Common pitfalls​

  • Validating a BST against direct children only. A node in the left subtree must be smaller than every ancestor it sits left of. Symptom: [5, 4, 6, null, null, 3, 7] is wrongly accepted.
  • Sentinel overflow: using math.MinInt as "no lower bound" fails when the tree contains math.MinInt. Pass bounds as pointers/nodes or flags.
  • Mixing up bottom-up and top-down state: a global "max so far" updated in the wrong place (Maximum Path Sum: the value you return upward is a single branch; the value you record may use both branches).
  • Deep recursion on skewed trees (10⁵ nodes in a line). Go copes better than many runtimes, but an iterative traversal makes memory explicit.
  • Duplicate keys in a BST without a stated policy (left, right, or a count field) — deletes then remove the wrong node.
  • Trie memory blow-up: [26]*node per node on millions of keys, or map[rune]*node per node with heavy map overhead. Measure, then compress.
  • Assuming a naive BST is balanced because test data was random; production keys (timestamps, sequential IDs) arrive sorted.

Interview angle​

  • Say which traversal and why: "post-order, because a node's answer depends on both children".
  • Define what your recursive function returns before writing it — most tree bugs come from an unclear contract.
  • Expected follow-ups: iterative version, O(1)-space traversal (Morris traversal, which temporarily rewires right pointers), serialization, handling a tree too big for memory.
  • Architect-level follow-ups: "How does a database index find a row?" (B+tree descent, page reads, why UUIDv4 primary keys fragment B+tree inserts — see Unique ID Generation), "B-tree vs LSM for a ledger write path?", "How would you build a real-time leaderboard?" (Real-time Gaming Leaderboard).
  • Red flags: not knowing that in-order of a BST is sorted, claiming BST operations are always O(log n), or no idea why databases do not use binary trees on disk.

Self-check​

1. Which traversal would you use to compute every subtree's sum, and why?

Post-order: a node's subtree sum is its value plus the sums of its left and right subtrees, so both children must be finished before the parent. It is the bottom-up recursion shape: each call returns its subtree's sum.

2. Why are BST operations O(n) in the worst case, and what fixes it?

Their cost is O(h), and inserting keys in sorted order makes each new key a child of the previous one, so h = n. Self-balancing trees (AVL, red-black) perform rotations on insert/delete to keep h = O(log n); B-trees stay balanced by splitting and merging nodes so all leaves have the same depth.

3. How do you delete a node with two children from a BST?

Find its in-order successor (the leftmost node of the right subtree), copy the successor's key into the node, then delete the successor from the right subtree. The successor has no left child, so that second delete is one of the easy cases (leaf or single child).

4. Why do databases use B+trees rather than red-black trees for indexes?

Storage reads whole pages. A B+tree packs hundreds of keys into each page-sized node, so the tree is only 3–4 levels deep for billions of rows and the top levels stay cached — a lookup costs one or two page reads. A binary tree would be ~30 levels deep, each level a potential random read. B+tree leaves are also linked, making range scans sequential.

5. How does iterative in-order traversal work?

Push nodes while walking left until nil. Pop one, visit it, then move to its right child and repeat the walk-left step. The stack always holds the path of ancestors whose left subtrees are in progress; it uses O(h) space.

6. What is the time complexity of finding all words with a given prefix in a trie versus a sorted slice?

Trie: O(L) to reach the prefix node plus the size of the output subtree. Sorted slice: O(L·log n) to binary-search the first string ≥ prefix, then scan forward while entries still have the prefix. The slice uses far less memory; the trie wins when prefix queries are very frequent and you also cache top-k results per node.

7. Scenario: a merchant-lookup service must autocomplete 2M merchant names with p99 under 10 ms. What structure do you choose?

Either a compressed trie (radix tree) with the top-k most popular completions cached at each node — O(prefix length) per query — or a sorted slice with binary search on the prefix range if memory matters more. Normalize input (case, accents), build the structure offline and swap it atomically, and shard by first characters if one node cannot hold it. See Search Autocomplete.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Build a merchant-name autocomplete package and measure it:

  1. Load 200k synthetic merchant names (lowercase ASCII) into (a) the Trie above and (b) a sorted []string using slices.BinarySearch to find the prefix range.
  2. Implement Complete(prefix, k) for both; verify they return identical results on 1,000 random prefixes.
  3. Benchmark query latency and report memory with runtime.ReadMemStats before and after loading.
  4. Bonus: add a popularity score and return the top-k by score using per-node cached results.

Done when both implementations agree, you have a table of ns/op and MB used for each, and a one-paragraph recommendation of which you would ship and why.

Further reading​

  • Introduction to Algorithms (CLRS) — chapters on binary search trees, red-black trees and B-trees
  • Robert Sedgewick, "Left-leaning Red-Black Trees" (2008), and Sedgewick & Wayne, Algorithms, 4th ed. — balanced search trees
  • Douglas Comer, "The Ubiquitous B-Tree" (ACM Computing Surveys, 1979)
  • Alex Petrov, Database Internals (O'Reilly, 2019) — B-tree chapters
  • github.com/google/btree — an in-memory B-tree for Go
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).