← Tree Traversal

Micro-Drill #196 — When to use which traversal order

Tree Traversal Target: 15s

The traversal order determines WHEN you process the root relative to children. Pick based on information flow direction.

TREE TRAVERSAL — WHEN TO USE WHICH
───────────────────────────────────
PREORDER (root → left → right):
  → Process root BEFORE children
  → Serialization, copying tree, prefix expression
  → "top-down" information passing

INORDER (left → root → right):
  → BST: gives sorted order!
  → Kth smallest, validate BST, convert BST to list

POSTORDER (left → right → root):
  → Process root AFTER children
  → "bottom-up" computation (height, size, subtree sums)
  → Delete tree, evaluate expression tree

LEVEL ORDER (BFS):
  → Level-by-level processing
  → Right side view, zigzag, level averages
  → Shortest path in unweighted tree

QUICK DECISION:
  Need sorted from BST?       → inorder
  Need to compute from leaves → postorder
  Need top-down propagation?  → preorder
  Need level-by-level?        → BFS

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #195 Micro #197 →