Zigzag Level Order Traversal in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to traverse a tree in zigzag order grows as the tree gets bigger.
Specifically, how does the number of nodes affect the steps taken?
Analyze the time complexity of the following code snippet.
function zigzagLevelOrder(root: TreeNode | null): number[][] {
if (!root) return [];
const result: number[][] = [];
const queue: TreeNode[] = [root];
let leftToRight = true;
while (queue.length) {
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);
leftToRight = !leftToRight;
}
return result;
}
This code visits each node of a binary tree level by level, alternating the order of values collected per level.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs once per tree level, and the inner for loop visits every node in that level.
- How many times: Every node in the tree is visited exactly once during the traversal.
As the number of nodes (n) grows, the code visits each node once, but unshift operations on level arrays add extra cost up to quadratic per level.
| Input Size (n) | Approx. Node Visits |
|---|---|
| 10 | About 10 visits and value insertions |
| 100 | About 100 visits and value insertions |
| 1000 | About 1000 visits and value insertions |
Pattern observation: Node visits grow linearly with n, but total time can grow quadratically due to unshift costs.
Time Complexity: O(n^2)
This means the time to complete the traversal can grow quadratically with the number of nodes in the worst case.
[OK] Correct thinking: "Because we use unshift inside the loop, the time complexity becomes quadratic."
Why: For a level with k nodes, k sequential unshifts take O(1 + 2 + ... + k) = O(k^2) time. Worst case k=Θ(n), so O(n^2) overall.
Understanding this traversal's time complexity helps you explain how tree traversals work efficiently, a common topic in interviews.
"What if we replaced the array unshift with a different data structure like a deque? How would that affect the time complexity?"
Practice
Zigzag Level Order Traversal of a binary tree?Solution
Step 1: Understand level order traversal
Normal level order traversal visits nodes level by level from left to right.Step 2: Identify zigzag pattern
Zigzag traversal alternates direction each level: left-to-right, then right-to-left, and so on.Final Answer:
Traverse each level of the tree alternating between left-to-right and right-to-left order -> Option CQuick Check:
Zigzag means alternating directions [OK]
- Thinking traversal is always left to right
- Confusing zigzag with normal level order
- Ignoring level-by-level traversal
Solution
Step 1: Identify correct queue initialization
In TypeScript, an array can be used as a queue with push and shift methods.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.Final Answer:
const queue: TreeNode[] = []; queue.push(root); -> Option DQuick Check:
Array with push is correct queue usage [OK]
- Using Set instead of queue
- Incorrect object initialization
- Using non-existent enqueue method
1 / \ 2 3 / \ \ 4 5 6
Solution
Step 1: Traverse level 0 left to right
Level 0 has node 1, so output is [1].Step 2: Traverse level 1 right to left
Level 1 nodes are 2 and 3; reversed order is [3, 2].Step 3: Traverse level 2 left to right
Level 2 nodes are 4, 5, 6; order is [4, 5, 6].Final Answer:
[[1], [3, 2], [4, 5, 6]] -> Option AQuick Check:
Zigzag alternates direction each level [OK]
- Not reversing nodes on odd levels
- Mixing node order at last level
- Confusing left and right children order
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
}
Solution
Step 1: Check direction toggle
The variable leftToRight controls direction but is never changed inside the loop.Step 2: Understand effect of missing toggle
Without toggling, direction stays same, so zigzag pattern breaks.Final Answer:
leftToRight is never toggled, so traversal direction never changes -> Option BQuick Check:
Toggle direction each level for zigzag [OK]
- Forgetting to toggle leftToRight
- Using wrong queue methods
- Incorrectly adding nodes to level array
Solution
Step 1: Understand current output format
Zigzag traversal usually returns nested arrays, one per level.Step 2: Modify to flat array
Instead of pushing level arrays, append each level's nodes to a single result array.Step 3: Keep zigzag order
Maintain alternating direction logic while flattening output.Final Answer:
Concatenate each level's nodes to a single array instead of pushing nested arrays -> Option AQuick Check:
Flatten by concatenation, keep zigzag order [OK]
- Changing traversal order incorrectly
- Using stack breaks level order
- Returning only partial nodes
Ready to prove it?
Pass the test and this pattern moves unknown
