Pattern #40

Tree BFS / Level Order Traversal

Important interview questions, thinking patterns, levelSize snapshot rule, BFS vs DFS comparison, Minimum Depth early stop, and Go code templates.

Must Solve

15 core questions — solve these first.

  1. 1.Binary Tree Level Order Traversal
    medium
  2. 2.Binary Tree Zigzag Level Order Traversal
    medium
  3. 3.Binary Tree Right Side View
    medium
  4. 4.Average of Levels in Binary Tree
    easy
  5. 5.Minimum Depth of Binary Tree
    easy
  6. 6.Maximum Width of Binary Tree
    medium
  7. 7.Find Largest Value in Each Tree Row
    medium
  8. 8.Populating Next Right Pointers in Each Node
    medium
  9. 9.Populating Next Right Pointers II
    medium
  10. 10.Cousins in Binary Tree
    easy
  11. 11.Even Odd Tree
    medium
  12. 12.Check Completeness of a Binary Tree
    medium
  13. 13.Add One Row to Tree
    medium
  14. 14.Deepest Leaves Sum
    medium
  15. 15.Find Bottom Left Tree Value
    medium

Also Important

8 more questions worth practicing.

  1. 16.N-ary Tree Level Order Traversal
    medium
  2. 17.Reverse Level Order Traversal
    medium
  3. 18.Vertical Order Traversal
    medium
  4. 19.Bottom View of Binary Tree
    medium
  5. 20.Top View of Binary Tree
    medium
  6. 21.Nodes at Distance K
    medium
  7. 22.Maximum Level Sum of a Binary Tree
    medium
  8. 23.Minimum Number of Operations to Sort a Binary Tree by Level
    medium

How to Think

  1. Need level by level traversal?Tree BFS + Queue (FIFO)
  2. Need nearest / minimum depth?BFS (reaches shallow nodes first)
  3. Need rightmost node of every level?Level Order + last element (i == levelSize - 1)
  4. Need largest / average / sum per level?BFS + levelSize aggregation loop
  5. Need zigzag order?BFS + alternate level direction flag

Go Tree BFS Level Order Template

Standard Level-by-Level Queue Loop in Go

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

// Tree BFS Level Order Traversal in Go
func levelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }

    result := [][]int{}
    queue := []*TreeNode{root}
    head := 0 // Efficient head pointer instead of re-slicing array!

    for head < len(queue) {
        levelSize := len(queue) - head // CRUCIAL: Snapshot queue size before processing level!
        currentLevel := make([]int, 0, levelSize)

        for i := 0; i < levelSize; i++ {
            node := queue[head]
            head++

            currentLevel = append(currentLevel, node.Val)

            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }

        result = append(result, currentLevel)
    }

    return result
}

👉 Total Time: O(N) | Space: O(W) where W = max tree width

The Golden Rule: Snapshot levelSize BEFORE the Loop

Before processing any level, snapshot levelSize = len(queue) - head! Process exactly that many nodes in the inner loop so that newly appended children are safely preserved for the NEXT level.

// Minimum Depth of Binary Tree using BFS (Early Stop!)
func minDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }

    queue := []*TreeNode{root}
    depth := 1

    for len(queue) > 0 {
        levelSize := len(queue)
        for i := 0; i < levelSize; i++ {
            node := queue[0]
            queue = queue[1:]

            // First leaf encountered in BFS is automatically at minimum depth!
            if node.Left == nil && node.Right == nil {
                return depth
            }

            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        depth++
    }
    return depth
}

👉 Time: O(N) worst case, but stops as soon as first shallow leaf is popped!

BFS vs DFS Comparison

Tree BFS (Queue FIFO)

Processes nodes level-by-level horizontally. Ideal for Level Order, Minimum Depth, Right Side View, Per-level Aggregations, Nearest Nodes. Memory = O(Width).

Tree DFS (Stack / Recursion)

Explores subtrees deep down vertically. Ideal for Height, Max Path Sum, Subtree DP, LCA, Root-to-Leaf Paths. Memory = O(Height).

Visual Memory Rule
LEVEL / NEAREST → Use Tree BFS (Queue FIFO)
PATH / SUBTREE  → Use Tree DFS (Recursion)
levelSize       → Snapshot len(queue) BEFORE inner loop
Min Depth       → BFS early stop on first leaf node
Right Side View → Take last element of each level slice

💡 Golden Rule: "Snapshot the current queue size, process exactly that many nodes, and everything you add belongs to the next level."

Common Interview Mistakes

1. Forgetting Level Size Snapshot

If you don't store levelSize = len(queue) before the inner loop, children get mixed with parents in the same level slice!

2. Repeatedly Slicing Queue in Go

Doing queue = queue[1:] repeatedly re-allocates slice headers. Use a logical head pointer index for cleaner memory usage.

3. Using DFS for Simple Level Problems

When the problem explicitly asks for level-by-level output or nearest nodes, use BFS rather than simulating level maps via DFS.

4. Returning Min Depth on Non-Leaf Nodes

A node with only one child is NOT a leaf! A true leaf node requires node.Left == nil && node.Right == nil.

Interview Rules

  1. 1. Level by level traversal? → Tree BFS
  2. 2. Queue structure? → FIFO (First In First Out)
  3. 3. Level slice separation? → Snapshot levelSize = len(queue) before inner loop
  4. 4. Minimum depth / nearest level? → BFS early stop on first leaf node
  5. 5. Right side view? → Append last node of each level slice (i == levelSize - 1)
  6. 6. Bottom left value? → First node of deepest level slice (i == 0)
  7. 7. Zigzag order? → BFS + direction flag toggle (leftToRight = !leftToRight)
  8. 8. Overall Complexity → Time: O(N) | Queue Space: O(W) where W is maximum tree width (O(N) worst case)

Small Rules

  1. Rule 1: Tree BFS always relies on a Queue FIFO structure.
  2. Rule 2: Always capture levelSize before adding children in the loop.
  3. Rule 3: BFS is strong for minimum depth because shallow levels are processed first.
  4. Rule 4: Per-level calculations (sum, average, max) aggregate inside the inner level loop.
  5. Rule 5: BFS space depends on maximum tree width, not height.

Production Thinking

Organization Level ProcessingProcessing employees by hierarchy level (CEO -> Managers -> Engineers)

UI / DOM Depth InspectionInspecting DOM component trees layer by layer for layout metrics

Shallow Nearby File SearchFinding nearest matching configuration files before deep recursive searches

Multi-hop Network DistanceEvaluating 1-hop, 2-hop, 3-hop network service dependencies

Remember This

Tree BFS        → Queue FIFO
Level Order     → levelSize
Process         → Current level only
Children        → Next level
Minimum depth   → First leaf found
Right side view → Last node
Bottom left     → First node
Zigzag          → Alternate direction
Time            → O(N)
Space           → O(Width)

💡 Golden Rule: "Snapshot the current queue size, process exactly that many nodes, and everything you add belongs to the next level."