Bird
Raised Fist0
DSA Goprogramming~20 mins

Zigzag Level Order Traversal in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Zigzag Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Zigzag Level Order Traversal on a Binary Tree
What is the output of the zigzag level order traversal for the given binary tree?
DSA Go
package main

import "fmt"

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

func zigzagLevelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }
    var result [][]int
    var currentLevel []*TreeNode
    currentLevel = append(currentLevel, root)
    leftToRight := true

    for len(currentLevel) > 0 {
        var levelVals []int
        var nextLevel []*TreeNode

        for _, node := range currentLevel {
            levelVals = append(levelVals, node.Val)
        }

        if !leftToRight {
            for i, j := 0, len(levelVals)-1; i < j; i, j = i+1, j-1 {
                levelVals[i], levelVals[j] = levelVals[j], levelVals[i]
            }
        }

        for _, node := range currentLevel {
            if node.Left != nil {
                nextLevel = append(nextLevel, node.Left)
            }
            if node.Right != nil {
                nextLevel = append(nextLevel, node.Right)
            }
        }

        result = append(result, levelVals)
        currentLevel = nextLevel
        leftToRight = !leftToRight
    }

    return result
}

func main() {
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 5}
    root.Right.Right = &TreeNode{Val: 6}

    result := zigzagLevelOrder(root)
    fmt.Println(result)
}
A[[1], [2, 3], [4, 5, 6]]
B[[1], [3, 2], [4, 5, 6]]
C[[1], [2, 3], [6, 5, 4]]
D[[1], [3, 2], [6, 5, 4]]
Attempts:
2 left
💡 Hint
Remember that zigzag means alternating the order of nodes at each level.
🧠 Conceptual
intermediate
1:30remaining
Understanding Zigzag Level Order Traversal Direction
In zigzag level order traversal, what determines the order of nodes at each level?
AThe level number: even levels left to right, odd levels right to left
BThe number of children a node has
CThe value of the node: even values left to right, odd values right to left
DThe height of the tree
Attempts:
2 left
💡 Hint
Think about how the traversal direction changes as you go down levels.
🔧 Debug
advanced
2:30remaining
Identify the Bug in Zigzag Traversal Code
What error will this code produce when run, and why? func zigzagLevelOrder(root *TreeNode) [][]int { if root == nil { return [][]int{} } var result [][]int var currentLevel []*TreeNode currentLevel = append(currentLevel, root) leftToRight := true for len(currentLevel) > 0 { var levelVals []int var nextLevel []*TreeNode for i := len(currentLevel) - 1; i >= 0; i-- { node := currentLevel[i] levelVals = append(levelVals, node.Val) if leftToRight { if node.Left != nil { nextLevel = append(nextLevel, node.Left) } if node.Right != nil { nextLevel = append(nextLevel, node.Right) } } else { if node.Right != nil { nextLevel = append(nextLevel, node.Right) } if node.Left != nil { nextLevel = append(nextLevel, node.Left) } } } result = append(result, levelVals) currentLevel = nextLevel leftToRight = !leftToRight } return result }
AThe code will panic due to nil pointer dereference
BThe code will cause an infinite loop
CThe code will run correctly and produce the expected zigzag output
DThe traversal order of nodes in nextLevel is incorrect, causing wrong zigzag output
Attempts:
2 left
💡 Hint
Check how nextLevel nodes are added and in what order.
🚀 Application
advanced
1:00remaining
Number of Levels in Zigzag Traversal Output
Given a binary tree with 7 nodes arranged as a complete binary tree of height 3, how many levels will the zigzag level order traversal output contain?
A3
B7
C4
D2
Attempts:
2 left
💡 Hint
Think about how many levels a complete binary tree of height 3 has.
❓ Predict Output
expert
3:00remaining
Output of Zigzag Traversal on Unbalanced Tree
What is the output of the zigzag level order traversal for this unbalanced binary tree? Tree structure: - Root: 10 - Root.Left: 5 - Root.Left.Left: 3 - Root.Left.Left.Left: 1 - Root.Right: 15 - Root.Right.Right: 20
DSA Go
package main

import "fmt"

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

func zigzagLevelOrder(root *TreeNode) [][]int {
    if root == nil {
        return [][]int{}
    }
    var result [][]int
    var currentLevel []*TreeNode
    currentLevel = append(currentLevel, root)
    leftToRight := true

    for len(currentLevel) > 0 {
        var levelVals []int
        var nextLevel []*TreeNode

        for _, node := range currentLevel {
            levelVals = append(levelVals, node.Val)
        }

        if !leftToRight {
            for i, j := 0, len(levelVals)-1; i < j; i, j = i+1, j-1 {
                levelVals[i], levelVals[j] = levelVals[j], levelVals[i]
            }
        }

        for _, node := range currentLevel {
            if node.Left != nil {
                nextLevel = append(nextLevel, node.Left)
            }
            if node.Right != nil {
                nextLevel = append(nextLevel, node.Right)
            }
        }

        result = append(result, levelVals)
        currentLevel = nextLevel
        leftToRight = !leftToRight
    }

    return result
}

func main() {
    root := &TreeNode{Val: 10}
    root.Left = &TreeNode{Val: 5}
    root.Left.Left = &TreeNode{Val: 3}
    root.Left.Left.Left = &TreeNode{Val: 1}
    root.Right = &TreeNode{Val: 15}
    root.Right.Right = &TreeNode{Val: 20}

    result := zigzagLevelOrder(root)
    fmt.Println(result)
}
A[[10], [15, 5], [20, 3], [1]]
B[[10], [5, 15], [3, 20], [1]]
C[[10], [15, 5], [3, 20], [1]]
D[[10], [5, 15], [20, 3], [1]]
Attempts:
2 left
💡 Hint
Remember to alternate the order of nodes at each level, even if the tree is unbalanced.

Practice

(1/5)
1. What does the Zigzag Level Order Traversal of a binary tree do differently compared to a normal level order traversal?
easy
A. It alternates the direction of traversal at each level, switching between left-to-right and right-to-left.
B. It only traverses the left subtree of the tree.
C. It visits nodes in a random order at each level.
D. It traverses nodes only in right-to-left order for all levels.

Solution

  1. Step 1: Understand normal level order traversal

    Normal level order traversal visits nodes level by level from left to right.
  2. Step 2: Identify zigzag difference

    Zigzag traversal changes direction every level: first left-to-right, then right-to-left, and so on.
  3. Final Answer:

    It alternates the direction of traversal at each level, switching between left-to-right and right-to-left. -> Option A
  4. Quick Check:

    Zigzag = alternate directions [OK]
Hint: Remember zigzag means direction flips each level [OK]
Common Mistakes:
  • Thinking traversal is always left-to-right
  • Confusing zigzag with random order
  • Ignoring direction change at each level
2. Which of the following Go code snippets correctly initializes a queue for level order traversal in Zigzag Level Order Traversal?
easy
A. queue := make([]int, 0)
B. queue := []int{root}
C. queue := map[int]*TreeNode{}
D. queue := []*TreeNode{root}

Solution

  1. Step 1: Identify the queue type needed

    Queue should hold pointers to TreeNode structs, so []*TreeNode is correct.
  2. Step 2: Check each option's correctness

    queue := []*TreeNode{root} uses []*TreeNode with root node, correct for traversal. Options A and B use int slices, wrong type. queue := map[int]*TreeNode{} uses map, not queue.
  3. Final Answer:

    queue := []*TreeNode{root} -> Option D
  4. Quick Check:

    Queue holds TreeNode pointers = queue := []*TreeNode{root} [OK]
Hint: Queue must hold TreeNode pointers, not ints or maps [OK]
Common Mistakes:
  • Using int slices instead of TreeNode pointers
  • Using map instead of slice for queue
  • Not initializing queue with root node
3. Given the binary tree:
    1
   / \
  2   3
 / \   \
4   5   6

What is the output of Zigzag Level Order Traversal?
medium
A. [[1], [2, 3], [4, 5, 6]]
B. [[1], [2, 3], [6, 5, 4]]
C. [[1], [3, 2], [4, 5, 6]]
D. [[1], [3, 2], [6, 5, 4]]

Solution

  1. Step 1: Traverse level 0 and 1 with direction

    Level 0: left-to-right -> [1]. Level 1: right-to-left -> [3, 2].
  2. Step 2: Traverse level 2 left-to-right

    Level 2 nodes: 4, 5, 6 from left to right -> [4, 5, 6].
  3. Final Answer:

    [[1], [3, 2], [4, 5, 6]] -> Option C
  4. Quick Check:

    Zigzag levels alternate directions = [[1], [3, 2], [4, 5, 6]] [OK]
Hint: Alternate direction each level, left-to-right then right-to-left [OK]
Common Mistakes:
  • Not reversing nodes on odd levels
  • Reversing nodes on even levels incorrectly
  • Mixing node order at last level
4. Consider this Go code snippet for Zigzag Level Order Traversal:
for len(queue) > 0 {
    levelSize := len(queue)
    var level []int
    for i := 0; i < levelSize; i++ {
        node := queue[0]
        queue = queue[1:]
        level = append(level, node.Val)
        if node.Left != nil {
            queue = append(queue, node.Left)
        }
        if node.Right != nil {
            queue = append(queue, node.Right)
        }
    }
    if leftToRight {
        result = append(result, level)
    } else {
        reverse(level)
        result = append(result, level)
    }
    leftToRight = !leftToRight
}

What is the main bug in this code?
medium
A. The reverse function is called but not defined or implemented.
B. The queue is not updated correctly after popping the first element.
C. The variable leftToRight is never initialized before use.
D. The level slice is appended before processing child nodes.

Solution

  1. Step 1: Check queue update correctness

    Queue is updated by slicing off first element correctly, no bug here.
  2. Step 2: Verify reverse function usage

    reverse(level) is called but no definition or implementation is shown, causing compile error.
  3. Final Answer:

    The reverse function is called but not defined or implemented. -> Option A
  4. Quick Check:

    Undefined reverse function causes error [OK]
Hint: Ensure all helper functions like reverse are implemented [OK]
Common Mistakes:
  • Assuming reverse is built-in in Go
  • Ignoring initialization of leftToRight (usually done before loop)
  • Misunderstanding queue slicing syntax
5. You want to implement Zigzag Level Order Traversal but optimize space by avoiding reversing slices. Which approach is best?
hard
A. Use a queue and reverse the slice after each level as usual.
B. Use two stacks to alternate pushing nodes in correct order per level.
C. Use recursion with a global list and reverse at the end.
D. Traverse all nodes left-to-right and then reverse the entire result.

Solution

  1. Step 1: Understand reversing cost

    Reversing slices after each level adds extra time and space overhead.
  2. Step 2: Use two stacks for order control

    Two stacks let you push child nodes in order that naturally produces zigzag traversal without reversing.
  3. Final Answer:

    Use two stacks to alternate pushing nodes in correct order per level. -> Option B
  4. Quick Check:

    Two stacks avoid reversing slices [OK]
Hint: Two stacks method avoids reversing slices [OK]
Common Mistakes:
  • Relying on reversing slices every level
  • Using recursion without order control
  • Reversing entire result instead of per level
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard