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?"