← All patterns
12 / 32
Trees & Recursion

Tree DFS · Preorder

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

preordercopy treecloneserializeprefixroot firstpaths from root
Practice

Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.

Ask yourself

  1. Act on a node before you descend — copy, clone, serialize?
  2. Building a path from the root downward?
  3. Recurse in order: visit, then left, then right.

Classic problem

Binary Tree Preorder Traversal — Visit root before children: root → left → right. Used when you need to process a node before its subtree (e.g., serialization, path problems).

Input: Binary tree with nodes A(root), B(left), C(right), D(B-left), E(B-right), F(C-left), G(C-right)

Output: [A, B, D, E, C, F, G] — root visited first at every subtree.

Watch it run

Common pitfalls

Forgetting the null base case.

Checking the sum at a null child instead of a true leaf (double-counts paths).