Zigzag Level Order Traversal in DSA C# - Time & Space Complexity
We want to understand how the time needed to traverse a tree in zigzag order changes as the tree grows.
Specifically, how does the number of nodes affect the work done?
Analyze the time complexity of the following code snippet.
public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
var result = new List<IList<int>>();
if (root == null) return result;
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
bool leftToRight = true;
while (queue.Count > 0) {
int size = queue.Count;
var level = new List<int>(size);
for (int i = 0; i < size; i++) {
var node = queue.Dequeue();
level.Add(node.val);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
if (!leftToRight) {
level.Reverse();
}
result.Add(level);
leftToRight = !leftToRight;
}
return result;
}
This code traverses a binary tree level by level, alternating the order of values between left-to-right and right-to-left.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once in the while loop and inner for loop.
- How many times: Each node is processed exactly once, so n times where n is the number of nodes.
As the number of nodes grows, the code visits each node once, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 node visits |
| 100 | About 100 node visits |
| 1000 | About 1000 node visits |
Pattern observation: The operations increase linearly as the tree size increases.
Time Complexity: O(n)
This means the time to complete the traversal grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "Reversing the list for every right-to-left level makes the time complexity worse than linear O(n²)."
[OK] Correct: Reversing a list of size k takes O(k) time, but the sum of all level sizes k is n, so total reversing time is O(n).
Understanding this traversal's time complexity helps you explain how tree traversals scale and shows you can analyze mixed operations in loops.
"What if we used a deque to add elements at both ends instead of reversing the list? How would the time complexity change?"
Practice
Solution
Step 1: Understand normal level order traversal
Normal level order traversal visits nodes level by level from left to right.Step 2: Identify zigzag difference
Zigzag traversal alternates direction each level: first left to right, then right to left, and so on.Final Answer:
It alternates the direction of traversal at each level, left to right then right to left. -> Option AQuick Check:
Zigzag = alternate directions [OK]
- Thinking it only visits left subtree
- Assuming traversal is always left to right
- Confusing zigzag with reverse order
Solution
Step 1: Identify data structure for BFS
Queue is used for breadth-first search to process nodes level by level.Step 2: Check code snippet correctness
Queue<TreeNode> queue = new Queue<TreeNode>(); correctly declares a Queue of TreeNode objects, suitable for traversal.Final Answer:
Queue<TreeNode> queue = new Queue<TreeNode>(); -> Option BQuick Check:
Queue for BFS = Queue<TreeNode> queue = new Queue<TreeNode>(); [OK]
- Using Stack instead of Queue for BFS
- Using List which lacks FIFO behavior
- Using Dictionary which is not suitable here
1 / \ 2 3 / \ \ 4 5 6
What is the output of zigzag level order traversal?
Solution
Step 1: Traverse level 0 left to right
Level 0 nodes: [1]Step 2: Traverse level 1 right to left
Level 1 nodes: [2, 3], reversed to [3, 2]Step 3: Traverse level 2 left to right
Level 2 nodes: [4, 5, 6]Final Answer:
[[1], [3, 2], [4, 5, 6]] -> Option AQuick Check:
Zigzag levels = [[1], [3, 2], [4, 5, 6]] [OK]
- Not reversing nodes on alternate levels
- Mixing node order in last level
- Confusing left and right child order
if (level % 2 == 0)
result.Add(currentLevel);
else
result.Add(currentLevel.Reverse().ToList());What is the bug in this code?
Solution
Step 1: Understand zigzag pattern
Zigzag reverses nodes on odd levels (1, 3, 5...), not even levels (0, 2, 4...).Step 2: Analyze code condition
The condition correctly identifies even/odd levels for reversal.Step 3: Identify the actual issue
currentLevel.Reverse() (List<TreeNode>.Reverse) modifies the list in place and returns void, causing side effects and a compilation error on .ToList().Final Answer:
It reverses the original list causing side effects. -> Option CQuick Check:
List.Reverse() in-place modifies original [OK]
- Reversing on even levels instead of odd
- Modifying original list causing bugs
- Not reversing at all
Solution
Step 1: Identify filtering requirement
We want only even-valued nodes in the output, so filter nodes during traversal.Step 2: Apply filtering during level collection
Filter nodes by checking if value is even before adding to current level list.Step 3: Keep zigzag logic intact
After filtering, apply zigzag reversal as usual on filtered nodes.Final Answer:
Filter nodes by even value before adding them to the current level list during traversal. -> Option DQuick Check:
Filter during traversal = Filter nodes by even value before adding them to the current level list during traversal. [OK]
- Reversing entire result instead of filtering
- Skipping reversal breaks zigzag pattern
- Using stack incorrectly for filtering
Ready to prove it?
Pass the test and this pattern moves unknown
