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. 1.Binary Tree Preorder Traversal
    easy
  2. 2.N-ary Tree Preorder Traversal
    easy
  3. 3.Flatten Binary Tree to Linked List
    medium
  4. 4.Serialize and Deserialize Binary Tree
    hard
  5. 5.Construct Binary Tree from Preorder and Inorder Traversal
    medium
  6. 6.Construct BST from Preorder Traversal
    medium
  7. 7.Binary Tree Paths
    easy
  8. 8.Path Sum
    easy
  9. 9.Path Sum II
    medium
  10. 10.Count Good Nodes in Binary Tree
    medium
  11. 11.Sum Root to Leaf Numbers
    medium
  12. 12.Maximum Difference Between Node and Ancestor
    medium
  13. 13.Copy / Clone Tree
    medium
  14. 14.Subtree Traversal Problems
    easy

Also Important

6 more questions worth practicing.

  1. 15.Recover a Tree From Preorder Traversal
    hard
  2. 16.Verify Preorder Serialization of a Binary Tree
    medium
  3. 17.Verify Preorder Sequence in BST
    medium
  4. 18.Boundary Traversal
    medium
  5. 19.Root-to-Leaf Path Problems
    easy
  6. 20.Flatten Multilevel Tree Variants
    medium

How to Think

  1. Need current node before children?Preorder Traversal (Root -> Left -> Right)
  2. Need root-to-leaf path / context?Preorder DFS + carry state DOWNWARD
  3. Need serialize tree shape?Preorder + nil markers "#"
  4. Need flatten tree root-first?Preorder order
  5. 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!

Visual Memory Rule
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

1. Mixing Traversal Orders

Preorder is strictly ROOT -> LEFT -> RIGHT. Do not confuse it with Inorder (LEFT -> ROOT -> RIGHT).

2. Wrong Stack Push Order

If you push LEFT then RIGHT, the stack pops RIGHT first! You MUST push node.Right first so node.Left pops first.

3. Forgetting Nil Base Case

Always check if root == nil { return } to prevent nil dereference runtime crashes.

4. Serializing Without Nil Markers

Node values alone cannot preserve tree shape! You MUST include nil markers (#) to uniquely reconstruct the tree.

Interview Rules

  1. 1. Root node processed first? → Preorder Traversal
  2. 2. Traversal sequence?ROOT -> LEFT -> RIGHT
  3. 3. Root-to-leaf paths? → Preorder DFS carrying state DOWNWARD
  4. 4. Iterative stack rule? → Push node.Right first, then node.Left
  5. 5. Tree flattening? → Flattened order matches Preorder traversal order
  6. 6. Tree serialization? → Preorder + nil markers (#)
  7. 7. Tree reconstruction? → Preorder first element is ROOT
  8. 8. Overall Complexity → Time: O(N) | Stack Space: O(H) (O(log N) balanced, O(N) skewed)

Small Rules

  1. Rule 1: Preorder visits the root node before visiting left and right subtrees.
  2. Rule 2: In iterative preorder, push node.Right first so node.Left pops first.
  3. Rule 3: Preorder naturally carries parent context downward to children.
  4. Rule 4: Preorder + nil markers preserves unique tree shape for serialization.
  5. Rule 5: Reconstructing trees from Preorder uses the first element as ROOT.

Production Thinking

File System SerializationSaving parent directory headers before listing child entries

UI Component ConfigurationApplying parent layout rules before configuring child widgets

Permission InheritanceEvaluating parent access controls before checking sub-folder permissions

Cascading Configuration TreesResolving 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."