Bird
Raised Fist0
DSA Javascriptprogramming

Zigzag Level Order Traversal in DSA Javascript

Choose your learning style10 modes available
Mental Model
We visit nodes level by level but alternate the direction of visiting nodes at each level.
Analogy: Imagine reading lines of text where you read the first line left to right, the second line right to left, then left to right again, like zigzagging across the page.
       1
      / \
     2   3
    / \   \
   4   5   6

Level 0: 1 (left to right)
Level 1: 3 -> 2 (right to left)
Level 2: 4 -> 5 -> 6 (left to right)
Dry Run Walkthrough
Input: Binary tree: 1 -> 2, 3 -> 4, 5, null, 6 (root 1, left 2, right 3, 2's children 4 and 5, 3's right child 6)
Goal: Traverse the tree level by level, alternating direction each level, collecting node values in zigzag order.
Step 1: Start at root level (level 0), direction left to right
Level 0: [1] -> null
Why: We begin traversal from the root node going left to right.
Step 2: Collect level 0 nodes: 1
Result so far: [[1]]
Why: First level nodes collected in left to right order.
Step 3: Move to level 1, direction right to left
Level 1: [3, 2] -> null
Why: Next level is traversed in opposite direction to zigzag.
Step 4: Collect level 1 nodes in right to left order: 3, 2
Result so far: [[1], [3, 2]]
Why: We reverse the order of nodes at this level.
Step 5: Move to level 2, direction left to right
Level 2: [4, 5, 6] -> null
Why: Direction alternates again for next level.
Step 6: Collect level 2 nodes in left to right order: 4, 5, 6
Result so far: [[1], [3, 2], [4, 5, 6]]
Why: Collect nodes in normal order at this level.
Result:
Final zigzag order: [[1], [3, 2], [4, 5, 6]]
Annotated Code
DSA Javascript
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function zigzagLevelOrder(root) {
  if (!root) return [];
  const result = [];
  const queue = [root];
  let leftToRight = true;

  while (queue.length > 0) {
    const levelSize = queue.length;
    const levelNodes = [];

    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();
      if (leftToRight) {
        levelNodes.push(node.val); // add normally
      } else {
        levelNodes.unshift(node.val); // add reversed
      }
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }

    result.push(levelNodes);
    leftToRight = !leftToRight; // flip direction
  }

  return result;
}

// Driver code
const root = new TreeNode(1,
  new TreeNode(2, new TreeNode(4), new TreeNode(5)),
  new TreeNode(3, null, new TreeNode(6))
);

console.log(zigzagLevelOrder(root));
if (!root) return [];
handle empty tree edge case
const queue = [root];
initialize queue with root for level order traversal
while (queue.length > 0) {
process nodes level by level until none left
const levelSize = queue.length;
number of nodes at current level
for (let i = 0; i < levelSize; i++) {
iterate over all nodes in current level
const node = queue.shift();
remove node from front of queue to process
if (leftToRight) { levelNodes.push(node.val); } else { levelNodes.unshift(node.val); }
add node value in normal or reversed order depending on direction
if (node.left) queue.push(node.left); if (node.right) queue.push(node.right);
add children to queue for next level
result.push(levelNodes);
save current level's collected nodes
leftToRight = !leftToRight;
flip direction for next level
OutputSuccess
[[1],[3,2],[4,5,6]]
Complexity Analysis
Time: O(n) because we visit each node exactly once during traversal
Space: O(n) because we store nodes in queue and result arrays proportional to number of nodes
vs Alternative: Compared to normal level order traversal, zigzag adds a small overhead of reversing order by unshift but still linear time overall
Edge Cases
Empty tree (root is null)
Returns empty array immediately
DSA Javascript
if (!root) return [];
Single node tree
Returns array with one level containing the single node value
DSA Javascript
const queue = [root];
Tree with only left or only right children
Traverses levels normally, zigzag order still applies but levels have single nodes
DSA Javascript
if (node.left) queue.push(node.left); if (node.right) queue.push(node.right);
When to Use This Pattern
When asked to traverse a tree level by level but with alternating directions each level, use zigzag level order traversal to collect nodes in the required order.
Common Mistakes
Mistake: Always appending nodes in the same order without reversing on alternate levels
Fix: Use unshift to add nodes at the front of the array on alternate levels to reverse order
Mistake: Modifying the queue while iterating causing incorrect level sizes
Fix: Store the current queue length before the loop to process exactly one level
Summary
Traverses a binary tree level by level, alternating the direction of node collection each level.
Use when you need to output tree nodes in zigzag or spiral order.
Flip the direction flag each level and add nodes accordingly to achieve zigzag pattern.

Practice

(1/5)
1. What is the main difference between a normal level order traversal and a zigzag level order traversal of a binary tree?
easy
A. Zigzag traversal visits nodes only on even levels.
B. Zigzag traversal alternates the direction of node visits at each level.
C. Zigzag traversal visits nodes in reverse order at all levels.
D. Zigzag traversal skips leaf nodes.

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: Understand zigzag traversal difference

    Zigzag traversal alternates direction: left to right on one level, then right to left on the next, and so on.
  3. Final Answer:

    Zigzag traversal alternates the direction of node visits at each level. -> Option B
  4. Quick Check:

    Zigzag = alternate directions [OK]
Hint: Remember zigzag means direction flips each level [OK]
Common Mistakes:
  • Thinking zigzag skips levels
  • Assuming zigzag always reverses order
  • Confusing zigzag with normal level order
2. Which of the following JavaScript code snippets correctly initializes a queue for level order traversal?
easy
A. const queue = new Set(); queue.add(root);
B. const queue = {}; queue.enqueue(root);
C. const queue = []; queue.push(root);
D. const queue = new Map(); queue.set(root);

Solution

  1. Step 1: Identify correct queue initialization in JavaScript

    JavaScript arrays can be used as queues with push and shift methods.
  2. Step 2: Check each option

    const queue = []; queue.push(root); uses an array and push method correctly. Options B, C, and D use incorrect data structures or methods for queue behavior.
  3. Final Answer:

    const queue = []; queue.push(root); -> Option C
  4. Quick Check:

    Array with push = queue [OK]
Hint: Use array push/shift for queue in JS [OK]
Common Mistakes:
  • Using Set or Map instead of array for queue
  • Using non-existent enqueue method
  • Initializing queue as an object
3. What is the output of the zigzag level order traversal for the binary tree below?
    1
   / \
  2   3
 / \   \
4   5   6
medium
A. [[1], [3, 2], [4, 5, 6]]
B. [[1], [2, 3], [6, 5, 4]]
C. [[1], [3, 2], [6, 5, 4]]
D. [[1], [2, 3], [4, 5, 6]]

Solution

  1. Step 1: Traverse level 0 left to right

    Level 0 nodes: [1]
  2. Step 2: Traverse level 1 right to left

    Level 1 nodes: [2, 3] reversed to [3, 2]
  3. Step 3: Traverse level 2 left to right

    Level 2 nodes: [4, 5, 6]
  4. Final Answer:

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

    Zigzag levels alternate direction [OK]
Hint: Alternate direction each level, start left to right [OK]
Common Mistakes:
  • Not reversing the order on odd levels
  • Reversing all levels
  • Mixing node values order
4. Consider this snippet for zigzag traversal:
while(queue.length) {
  let levelSize = queue.length;
  let levelNodes = [];
  for(let i = 0; i < levelSize; i++) {
    let node = queue.shift();
    levelNodes.push(node.val);
    if(node.left) queue.push(node.left);
    if(node.right) queue.push(node.right);
  }
  if(reverse) levelNodes.reverse();
  result.push(levelNodes);
  reverse = !reverse;
}
What is the bug in this code?
medium
A. The variable 'reverse' is not initialized before the loop.
B. Using queue.shift() causes runtime error.
C. levelNodes.reverse() should be called before pushing nodes.
D. Children nodes should be pushed after reversing levelNodes.

Solution

  1. Step 1: Check variable initialization

    The variable 'reverse' is used but not declared or initialized before the loop, causing a ReferenceError.
  2. Step 2: Verify other code parts

    queue.shift() is valid for arrays, reversing after collecting nodes is correct, and pushing children before reversing is standard.
  3. Final Answer:

    The variable 'reverse' is not initialized before the loop. -> Option A
  4. Quick Check:

    Uninitialized variable 'reverse' causes error [OK]
Hint: Always initialize flags before loops [OK]
Common Mistakes:
  • Assuming shift() is invalid
  • Reversing nodes before collecting children
  • Pushing children after reversing level nodes
5. You want to implement zigzag level order traversal but optimize space by avoiding reversing arrays. Which approach below correctly achieves this?
hard
A. Use a deque and insert nodes at front or back depending on direction.
B. Use a queue and reverse the entire result array at the end.
C. Use recursion and collect nodes in normal order only.
D. Use two stacks, one for current level and one for next level, alternating push order.

Solution

  1. Step 1: Understand reversing avoidance

    Reversing arrays costs extra time and space; using two stacks can avoid this by controlling push order.
  2. Step 2: Analyze options

    Use two stacks, one for current level and one for next level, alternating push order. uses two stacks and alternates push order to get zigzag without reversing. Use a deque and insert nodes at front or back depending on direction. needs a deque which is not native in JS. Use a queue and reverse the entire result array at the end. reverses at the end, not avoiding reversing. Use recursion and collect nodes in normal order only. does not handle zigzag properly.
  3. Final Answer:

    Use two stacks, one for current level and one for next level, alternating push order. -> Option D
  4. Quick Check:

    Two stacks alternate push order = no reverse [OK]
Hint: Two stacks alternate push order to avoid reversing [OK]
Common Mistakes:
  • Using queue and reversing result at end
  • Trying recursion without direction control
  • Assuming deque is native in JavaScript
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