Zigzag Level Order Traversal in DSA Java - Time & Space Complexity
We want to understand how the time needed to traverse a tree in zigzag order changes as the tree grows.
How does the number of steps grow when the tree has more nodes?
Analyze the time complexity of the following code snippet.
public List> zigzagLevelOrder(TreeNode root) {
List> result = new ArrayList<>();
if (root == null) return result;
Queue queue = new LinkedList<>();
queue.offer(root);
boolean leftToRight = true;
while (!queue.isEmpty()) {
int size = queue.size();
LinkedList level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (leftToRight) level.addLast(node.val);
else level.addFirst(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(level);
leftToRight = !leftToRight;
}
return result;
}
This code visits each node of a binary tree level by level, alternating the order of values collected at each level.
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 one time.
As the number of nodes increases, the steps increase roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to complete the traversal grows directly with the number of nodes in the tree.
[X] Wrong: "Because of the zigzag pattern, the traversal takes more than linear time."
[OK] Correct: The zigzag only changes the order of adding values, but each node is still visited once, so time grows linearly.
Understanding this traversal helps you show you can handle tree traversals with variations, a common skill interviewers look for.
"What if we used a depth-first search instead of breadth-first search for zigzag traversal? 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: Understand zigzag traversal difference
Zigzag traversal changes direction at each level, alternating between left-to-right and right-to-left.Final Answer:
Zigzag traversal alternates the direction of node visits at each level. -> Option AQuick Check:
Zigzag = alternate direction [OK]
- Thinking zigzag visits only odd levels
- Assuming zigzag always goes right to left
- Confusing zigzag with random order
Solution
Step 1: Identify correct queue implementation
Java's Queue interface is commonly implemented by LinkedList for FIFO behavior.Step 2: Check other options
ArrayList is a list, not a queue; Stack is LIFO, not queue; HashSet is a set, no order.Final Answer:
Queue<TreeNode> queue = new LinkedList<>(); -> Option DQuick Check:
Queue = LinkedList [OK]
- Using ArrayList instead of Queue
- Using Stack which is LIFO, not FIFO
- Using HashSet which has no order
1
/ \
2 3
/ \ \
4 5 6
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 alternate direction [OK]
- Not reversing nodes on odd levels
- Reversing nodes on even levels incorrectly
- Mixing node order at last level
Queue<TreeNode> queue = new LinkedList<>();
boolean leftToRight = true;
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (leftToRight) level.add(node.val);
else level.add(0, node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
leftToRight = !leftToRight;
}
Solution
Step 1: Analyze for loop condition
The loop runs from i = 0 to i <= size, which means it runs size+1 times, causing poll() to return null once.Step 2: Correct loop condition
The loop should run exactly size times, so condition must be i < size.Final Answer:
The for loop condition should be i < size, not i <= size. -> Option CQuick Check:
Loop runs size times [OK]
- Using i <= size causing extra iteration
- Using Stack instead of Queue
- Not toggling direction flag
Solution
Step 1: Understand deque usage for zigzag
For left-to-right levels, add children at the end and remove nodes from front to process in order.Step 2: Reverse direction for right-to-left levels
For right-to-left levels, add children at front and remove nodes from end to process in reverse order.Final Answer:
Use deque to add nodes at the end for left-to-right levels and remove from front; add nodes at front for right-to-left levels and remove from end. -> Option BQuick Check:
Deque add/remove ends alternate by level [OK]
- Adding/removing from same end always
- Not reversing add/remove ends per level
- Using only queue or stack instead of deque
Ready to prove it?
Pass the test and this pattern moves unknown
