Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Zigzag Level Order Traversal in DSA Typescript - 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 simple tree
What is the output of the zigzag level order traversal for the given binary tree?
DSA Typescript
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

function zigzagLevelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const result: number[][] = [];
  let currentLevel: TreeNode[] = [root];
  let leftToRight = true;

  while (currentLevel.length > 0) {
    const levelValues: number[] = [];
    const nextLevel: TreeNode[] = [];

    for (const node of currentLevel) {
      levelValues.push(node.val);
      if (node.left) nextLevel.push(node.left);
      if (node.right) nextLevel.push(node.right);
    }

    if (!leftToRight) levelValues.reverse();
    result.push(levelValues);
    currentLevel = nextLevel;
    leftToRight = !leftToRight;
  }

  return result;
}

// Tree structure:
//     1
//    / \
//   2   3
//  / \   \
// 4   5   6

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));
A[[1],[3,2],[6,5,4]]
B[[1],[2,3],[4,5,6]]
C[[1],[2,3],[6,5,4]]
D[[1],[3,2],[4,5,6]]
Attempts:
2 left
💡 Hint
Remember that the traversal direction alternates at each level.
❓ Predict Output
intermediate
1:00remaining
Zigzag traversal output for a single-node tree
What is the output of the zigzag level order traversal for a tree with only one node (value 10)?
DSA Typescript
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

function zigzagLevelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const result: number[][] = [];
  let currentLevel: TreeNode[] = [root];
  let leftToRight = true;

  while (currentLevel.length > 0) {
    const levelValues: number[] = [];
    const nextLevel: TreeNode[] = [];

    for (const node of currentLevel) {
      levelValues.push(node.val);
      if (node.left) nextLevel.push(node.left);
      if (node.right) nextLevel.push(node.right);
    }

    if (!leftToRight) levelValues.reverse();
    result.push(levelValues);
    currentLevel = nextLevel;
    leftToRight = !leftToRight;
  }

  return result;
}

const root = new TreeNode(10);
console.log(zigzagLevelOrder(root));
A[[10]]
B[]
C[[10],[10]]
D[[0]]
Attempts:
2 left
💡 Hint
A single node means only one level to traverse.
🔧 Debug
advanced
2:00remaining
Identify the error in zigzag traversal code
What error will this code produce when run?
DSA Typescript
function zigzagLevelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const result: number[][] = [];
  let currentLevel: TreeNode[] = [root];
  let leftToRight = true;

  while (currentLevel.length > 0) {
    const levelValues: number[] = [];
    const nextLevel: TreeNode[] = [];

    for (let i = currentLevel.length - 1; i >= 0; i--) {
      const node = currentLevel[i];
      levelValues.push(node.val);
      if (node.left) nextLevel.push(node.left);
      if (node.right) nextLevel.push(node.right);
    }

    if (!leftToRight) levelValues.reverse();
    result.push(levelValues);
    currentLevel = nextLevel;
    leftToRight = !leftToRight;
  }

  return result;
}
ATypeError: Cannot read property 'val' of undefined
BSyntaxError due to missing colon
CThe traversal order is incorrect, but no runtime error
DInfinite loop causing timeout
Attempts:
2 left
💡 Hint
Check how nextLevel nodes are added when iterating backwards.
🧠 Conceptual
advanced
1:30remaining
Why use two stacks in zigzag traversal?
Why is using two stacks a common approach for zigzag level order traversal?
ABecause stacks allow reversing the order of nodes easily at each level
BBecause stacks reduce memory usage compared to queues
CBecause stacks automatically sort nodes by value
DBecause stacks prevent visiting nodes multiple times
Attempts:
2 left
💡 Hint
Think about how to reverse the order of nodes at alternate levels.
🚀 Application
expert
3:00remaining
Zigzag traversal output for an unbalanced tree
Given the unbalanced binary tree below, what is the zigzag level order traversal output? // Tree structure: // 7 // / \ // 9 8 // \ \ // 6 5 // / / // 1 4 // \ // 3
DSA Typescript
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

const root = new TreeNode(7,
  new TreeNode(9, null, new TreeNode(6, new TreeNode(1), null)),
  new TreeNode(8, null, new TreeNode(5, new TreeNode(4, null, new TreeNode(3)), null))
);

function zigzagLevelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const result: number[][] = [];
  let currentLevel: TreeNode[] = [root];
  let leftToRight = true;

  while (currentLevel.length > 0) {
    const levelValues: number[] = [];
    const nextLevel: TreeNode[] = [];

    for (const node of currentLevel) {
      levelValues.push(node.val);
      if (node.left) nextLevel.push(node.left);
      if (node.right) nextLevel.push(node.right);
    }

    if (!leftToRight) levelValues.reverse();
    result.push(levelValues);
    currentLevel = nextLevel;
    leftToRight = !leftToRight;
  }

  return result;
}

console.log(zigzagLevelOrder(root));
A[[7],[9,8],[5,6],[1,4],[3]]
B[[7],[8,9],[6,5],[4,1],[3]]
C[[7],[8,9],[5,6],[4,1],[3]]
D[[7],[9,8],[6,5],[1,4],[3]]
Attempts:
2 left
💡 Hint
Follow the zigzag pattern carefully level by level.

Practice

(1/5)
1. What is the main idea behind Zigzag Level Order Traversal of a binary tree?
easy
A. Traverse the tree only from right to left at all levels
B. Traverse the tree only from left to right at all levels
C. Traverse each level of the tree alternating between left-to-right and right-to-left order
D. Traverse nodes in random order without level consideration

Solution

  1. Step 1: Understand level order traversal

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

    Zigzag traversal alternates direction each level: left-to-right, then right-to-left, and so on.
  3. Final Answer:

    Traverse each level of the tree alternating between left-to-right and right-to-left order -> Option C
  4. Quick Check:

    Zigzag means alternating directions [OK]
Hint: Remember zigzag means switching direction each level [OK]
Common Mistakes:
  • Thinking traversal is always left to right
  • Confusing zigzag with normal level order
  • Ignoring level-by-level traversal
2. Which of the following TypeScript code snippets correctly initializes a queue for level order traversal?
easy
A. const queue = {}; queue.enqueue(root);
B. const queue = new Set<TreeNode>(); queue.add(root);
C. const queue: TreeNode[] = new TreeNode(); queue.push(root);
D. const queue: TreeNode[] = []; queue.push(root);

Solution

  1. Step 1: Identify correct queue initialization

    In TypeScript, an array can be used as a queue with push and shift methods.
  2. Step 2: Check each option

    const queue: TreeNode[] = []; queue.push(root); correctly declares an array and pushes root node. Others use wrong types or methods.
  3. Final Answer:

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

    Array with push is correct queue usage [OK]
Hint: Use array push/shift for queue in TypeScript [OK]
Common Mistakes:
  • Using Set instead of queue
  • Incorrect object initialization
  • Using non-existent enqueue method
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 has node 1, so output is [1].
  2. Step 2: Traverse level 1 right to left

    Level 1 nodes are 2 and 3; reversed order is [3, 2].
  3. Step 3: Traverse level 2 left to right

    Level 2 nodes are 4, 5, 6; order is [4, 5, 6].
  4. Final Answer:

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

    Zigzag alternates direction each level [OK]
Hint: Alternate direction each level starting left-to-right [OK]
Common Mistakes:
  • Not reversing nodes on odd levels
  • Mixing node order at last level
  • Confusing left and right children order
4. Consider this TypeScript code snippet for zigzag traversal. What is the bug?
const result: number[][] = [];
const queue: TreeNode[] = [root];
let leftToRight = true;
while (queue.length > 0) {
  const levelSize = queue.length;
  const levelNodes: number[] = [];
  for (let i = 0; i < levelSize; i++) {
    const node = queue.shift()!;
    if (leftToRight) levelNodes.push(node.val);
    else levelNodes.unshift(node.val);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  result.push(levelNodes);
  // Missing toggle of leftToRight
}
medium
A. Children nodes are pushed in wrong order
B. leftToRight is never toggled, so traversal direction never changes
C. levelNodes.unshift() should be levelNodes.push() always
D. queue.shift() is used instead of queue.pop() causing wrong order

Solution

  1. Step 1: Check direction toggle

    The variable leftToRight controls direction but is never changed inside the loop.
  2. Step 2: Understand effect of missing toggle

    Without toggling, direction stays same, so zigzag pattern breaks.
  3. Final Answer:

    leftToRight is never toggled, so traversal direction never changes -> Option B
  4. Quick Check:

    Toggle direction each level for zigzag [OK]
Hint: Toggle direction flag after each level [OK]
Common Mistakes:
  • Forgetting to toggle leftToRight
  • Using wrong queue methods
  • Incorrectly adding nodes to level array
5. Given a binary tree, how would you modify the zigzag level order traversal to return a flat array of node values in zigzag order instead of nested arrays per level?
hard
A. Concatenate each level's nodes to a single array instead of pushing nested arrays
B. Use a stack instead of a queue for traversal
C. Traverse all nodes left to right ignoring zigzag
D. Return only the last level's nodes

Solution

  1. Step 1: Understand current output format

    Zigzag traversal usually returns nested arrays, one per level.
  2. Step 2: Modify to flat array

    Instead of pushing level arrays, append each level's nodes to a single result array.
  3. Step 3: Keep zigzag order

    Maintain alternating direction logic while flattening output.
  4. Final Answer:

    Concatenate each level's nodes to a single array instead of pushing nested arrays -> Option A
  5. Quick Check:

    Flatten by concatenation, keep zigzag order [OK]
Hint: Append levels to one array instead of nested arrays [OK]
Common Mistakes:
  • Changing traversal order incorrectly
  • Using stack breaks level order
  • Returning only partial nodes
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