Coding Interview: Patterns & DSA · Trees & Graphs · Lesson 1 of 3
Tree traversals
A binary tree has nodes with a left and right child. Traversal is how you visit every node; the order you choose determines what you can compute. The three depth-first orders differ only in when you touch the current node relative to its children.
- Inorder (left, node, right): on a binary search tree this yields values in sorted order.
- Preorder (node, left, right): visits the root first — used to copy/serialize a tree.
- Postorder (left, right, node): children before parent — used to delete a tree or compute values that depend on subtrees (like height).
- Level-order (BFS): visit level by level using a queue — for shortest depth and level-based answers.
def inorder(node, out): if not node: return inorder(node.left, out) out.append(node.val) # visit between children inorder(node.right, out) def max_depth(node): if not node: return 0 return 1 + max(max_depth(node.left), max_depth(node.right))
BST inorder is sortedThe single most useful tree fact for interviews: an inorder traversal of a binary search tree emits its keys in ascending order. Validating a BST, finding the kth-smallest, and range queries all fall out of this.
Recursion depthA recursive traversal uses
O(h) stack space where h is the tree height — O(log n) if balanced but O(n) for a degenerate (linked-list-shaped) tree. Mention it.◆ Lock it in
- Inorder of a BST is sorted — the key interview fact.
- Preorder copies/serializes; postorder computes subtree-dependent values.
- Traversal uses
O(h)stack space —O(n)in the worst (skewed) case.
Feynman drill — say it out loudExplain why inorder traversal of a BST produces sorted output, using the BST ordering property.
Step 1 rate your confidence · Step 2 pick your answer
Which traversal of a binary SEARCH tree yields the keys in ascending sorted order?
Step 1 — how sure are you?