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.
vector> zigzagLevelOrder(TreeNode* root) {
vector> result;
if (!root) return result;
queue q; q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector level(size);
for (int i = 0; i < size; ++i) {
TreeNode* node = q.front(); q.pop();
int index = leftToRight ? i : (size - 1 - i);
level[index] = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
leftToRight = !leftToRight;
result.push_back(level);
}
return result;
}
This code visits each node level by level, alternating the order of values collected to create a zigzag pattern.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once in the tree.
- How many times: Exactly once per node, inside the while loop and for loop combined.
As the number of nodes (n) increases, the code visits each node once, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly as the tree size grows.
Time Complexity: O(n)
This means the time needed grows directly in proportion to 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 values collected, but each node is still visited once, so the time stays linear.
Understanding this traversal helps you show you can handle tree traversals with order changes, a common interview skill.
"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 level order traversal
Level order traversal visits nodes level by level from left to right.Step 2: Add zigzag pattern
Zigzag means alternate direction each level: first left to right, then right to left, and so on.Final Answer:
Traverse nodes level by level, alternating left to right and right to left -> Option AQuick Check:
Zigzag = alternate directions [OK]
- Thinking traversal is always left to right
- Confusing zigzag with preorder or inorder traversal
- Ignoring the alternating direction pattern
Solution
Step 1: Identify correct data structure for level order
Level order traversal uses a queue to process nodes FIFO (first in, first out).Step 2: Check code snippets
std::queue q; q.push(root); uses std::queue and pushes root correctly. Others use stack, vector, or list incorrectly for this purpose.Final Answer:
std::queue q; q.push(root); -> Option DQuick Check:
Queue for level order = std::queue q; q.push(root); [OK]
- Using stack instead of queue
- Using vector push_back but no FIFO behavior
- Using list with push_front which reverses order
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. Zigzag means reverse order here: [3, 2].Step 3: Traverse level 2 left to right
Level 2 nodes are 4, 5, 6 from left to right: [4, 5, 6].Final Answer:
[[1], [3, 2], [4, 5, 6]] -> Option AQuick Check:
Zigzag levels alternate direction [OK]
- Not reversing order on alternate levels
- Mixing node order at last level
- Confusing left and right child order
std::vector zigzagLevelOrder(TreeNode* root) {
std::vector result;
if (!root) return result;
std::queue q;
q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
std::vector<int> level(size);
for (int i = 0; i < size; ++i) {
TreeNode* node = q.front(); q.pop();
int index = leftToRight ? i : size - i - 1;
level[index] = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
result.push_back(level);
}
return result;
}Solution
Step 1: Analyze loop for toggling direction
The variable leftToRight controls direction but is never changed inside the loop.Step 2: Identify missing toggle
Without toggling leftToRight = !leftToRight; after processing each level, zigzag pattern won't alternate.Final Answer:
Missing toggle of leftToRight after each level -> Option CQuick Check:
Toggle direction each level [OK]
- Forgetting to flip leftToRight boolean
- Incorrect indexing in level vector
- Not pushing child nodes properly
1 / \ 2 3 / \ 4 5The output should be:
[1, 3, 2, 4, 5]Solution
Step 1: Perform standard zigzag traversal
Use queue and toggle direction each level to get vector of vectors with zigzag order.Step 2: Flatten the vector of vectors
Combine all inner vectors into a single vector preserving order to get flat list.Final Answer:
Perform normal zigzag traversal, then flatten the result vectors into one vector -> Option BQuick Check:
Flatten zigzag levels to one vector [OK]
- Trying to zigzag directly into flat vector without levels
- Using stack incorrectly for zigzag
- Ignoring zigzag pattern and traversing left to right only
Ready to prove it?
Pass the test and this pattern moves unknown
