Pattern #41
Preorder Traversal
Important interview questions, thinking patterns, Root-First (R-L-R) processing, Iterative Stack logic (push Right first), Serialization with null markers, and Go templates.
Must Solve
14 core questions — solve these first.
- 1.Binary Tree Preorder TraversalRoot -> Left -> Right: process node value before recursing left & right subtreeseasy
- 2.N-ary Tree Preorder TraversalProcess node value then iterate for _, child := range node.Childreneasy
- 3.Flatten Binary Tree to Linked ListPreorder traversal order: rewire right pointers while maintaining left = nilmedium
- 4.Serialize and Deserialize Binary TreePreorder traversal with nil markers "#" (e.g. 1,2,#,#,3,#,#)hard
- 5.Construct Binary Tree from Preorder and Inorder TraversalPreorder first value = root; Inorder index splits left & right subtreesmedium
- 6.Construct BST from Preorder TraversalFirst value = root; pass upper bound down recursion or use stackmedium
- 7.Binary Tree PathsPreorder DFS carrying current string path downward to leaveseasy
- 8.Path SumPreorder DFS carrying targetSum - node.Val downward to leaf nodeseasy
- 9.Path Sum IIPreorder DFS + Backtracking: append node -> recurse subtrees -> remove nodemedium
- 10.Count Good Nodes in Binary TreePreorder DFS carrying maxValSeen downward to childrenmedium
- 11.Sum Root to Leaf NumbersPreorder DFS carrying current number accumulator (curr * 10 + node.Val) downwardmedium
- 12.Maximum Difference Between Node and AncestorPreorder DFS carrying minVal & maxVal seen so far downward to leavesmedium
- 13.Copy / Clone TreePreorder traversal instantiating new TreeNode(root.Val) before childrenmedium
- 14.Subtree Traversal ProblemsPreorder check: isSameTree(node, subRoot) || isSubtree(node.Left) || isSubtree(node.Right)easy
Also Important
6 more questions worth practicing.
- 15.Recover a Tree From Preorder TraversalParse depth dashes "-" in preorder string using monotonic stackhard
- 16.Verify Preorder Serialization of a Binary TreeDegree counting: initial slot = 1, non-null node consumes 1 slot & adds 2 slotsmedium
- 17.Verify Preorder Sequence in BSTMonotonic stack tracking min lower bound as you move rightmedium
- 18.Boundary TraversalPreorder for left boundary -> leaves -> right boundary bottom-upmedium
- 19.Root-to-Leaf Path ProblemsPreorder DFS passing parent context downward to leaveseasy
- 20.Flatten Multilevel Tree VariantsPreorder flattening for doubly linked lists with child pointersmedium
How to Think
- Need current node before children?Preorder Traversal (Root -> Left -> Right)
- Need root-to-leaf path / context?Preorder DFS + carry state DOWNWARD
- Need serialize tree shape?Preorder + nil markers "#"
- Need flatten tree root-first?Preorder order
- Need build tree from preorder?First value is ROOT!
Go Preorder Code Templates
Recursive & Iterative Preorder in Go
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 1. Recursive Preorder: Root -> Left -> Right
func preorderRecursive(root *TreeNode) []int {
result := []int{}
var dfs func(node *TreeNode)
dfs = func(node *TreeNode) {
if node == nil {
return
}
result = append(result, node.Val) // Process Root First!
dfs(node.Left)
dfs(node.Right)
}
dfs(root)
return result
}
// 2. Iterative Preorder: Explicit Stack LIFO (Push RIGHT first!)
func preorderIterative(root *TreeNode) []int {
if root == nil {
return nil
}
result := []int{}
stack := []*TreeNode{root}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
result = append(result, node.Val)
// Push RIGHT first so LEFT is on top and pops first!
if node.Right != nil {
stack = append(stack, node.Right)
}
if node.Left != nil {
stack = append(stack, node.Left)
}
}
return result
}👉 Total Time: O(N) | Space: O(H) stack
Iterative Stack Rule: Push RIGHT First
Because stacks operate in LIFO (Last In First Out) order, pushing node.Right onto the stack before node.Left guarantees that node.Left sits at the top of the stack and gets processed first!
Serialization & Rebuilding Trees from Preorder
1. Serialization with Null Markers (#): A Preorder string like "1,2,#,#,3,#,#" uniquely encodes tree shape because # explicit null pointers record leaf boundaries.
2. Construct from Preorder + Inorder: The first element of Preorder is ALWAYS the root node. Locating that root in the Inorder array splits the remaining elements into left and right subtrees!
Preorder → ROOT -> LEFT -> RIGHT (Parent processed before children)
Iterative Stack → Push RIGHT first so LEFT pops first
State Flow → Parent passes parameters DOWNWARD to children
Serialization → Preorder + nil markers (#)
Tree Build → Preorder first element = ROOT💡 Golden Rule: "Process the parent first, then let that information flow down through the left and right subtrees."
Common Interview Mistakes
Preorder is strictly ROOT -> LEFT -> RIGHT. Do not confuse it with Inorder (LEFT -> ROOT -> RIGHT).
If you push LEFT then RIGHT, the stack pops RIGHT first! You MUST push node.Right first so node.Left pops first.
Always check if root == nil { return } to prevent nil dereference runtime crashes.
Node values alone cannot preserve tree shape! You MUST include nil markers (#) to uniquely reconstruct the tree.
Interview Rules
- 1. Root node processed first? → Preorder Traversal
- 2. Traversal sequence? →
ROOT -> LEFT -> RIGHT - 3. Root-to-leaf paths? → Preorder DFS carrying state DOWNWARD
- 4. Iterative stack rule? → Push
node.Rightfirst, thennode.Left - 5. Tree flattening? → Flattened order matches Preorder traversal order
- 6. Tree serialization? → Preorder + nil markers (
#) - 7. Tree reconstruction? → Preorder first element is ROOT
- 8. Overall Complexity → Time:
O(N)| Stack Space:O(H)(O(log N)balanced,O(N)skewed)
Small Rules
- Rule 1: Preorder visits the root node before visiting left and right subtrees.
- Rule 2: In iterative preorder, push node.Right first so node.Left pops first.
- Rule 3: Preorder naturally carries parent context downward to children.
- Rule 4: Preorder + nil markers preserves unique tree shape for serialization.
- Rule 5: Reconstructing trees from Preorder uses the first element as ROOT.
Production Thinking
File System Serialization → Saving parent directory headers before listing child entries
UI Component Configuration → Applying parent layout rules before configuring child widgets
Permission Inheritance → Evaluating parent access controls before checking sub-folder permissions
Cascading Configuration Trees → Resolving base configuration before evaluating child overrides
Remember This
Preorder → ROOT -> LEFT -> RIGHT
Root → Process first
Path / State → Pass downward
Recursive → Node, Left, Right
Iterative Stack → Push RIGHT then LEFT
Flatten → Preorder
Serialize → Preorder + nil markers
Tree Build → Preorder first val = ROOT
Time → O(N)💡 Golden Rule: "Process the parent first, then let that information flow down through the left and right subtrees."