DSA
Binary Tree Zigzag Level Order Traversal
Binary Trees. Time O(n), Space O(n).
Practice here
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Implementation (BFS - Breadth-First Search)#
- Intuition: Standard BFS processes nodes left-to-right on every level. To produce a zigzag, you only need to reverse the collected values of every odd-numbered level — the traversal order itself stays the same, only the output array is flipped.
- Mechanics: A levelId counter tracks the current level. All nodes at the current level are dequeued and their values pushed into a temporary vector. If levelId is odd, the vector is reversed before being added to the result. Children are always enqueued left-then-right regardless of direction.
- Trade-off: Reversing after collection is O(w) per level (w = level width) and adds negligible cost relative to the O(n) BFS. An alternative is to use a deque and push from the front or back depending on direction, avoiding explicit reversal — both strategies are O(n) overall.
Visit all nodes at level 0 → then level 1 → then level 2 → …
Perform normal level-order traversal using a queue, but reverse the order of values every alternate level to simulate the zig-zag pattern.
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if(!root)
return {};
vector<vector<int>> traversalResult;
queue<TreeNode*> q;
q.push(root);
int levelId = 0;
while(!q.empty())
{
int size = q.size();
vector<int> levelResult;
for(int i=0;i<size;i++)
{
TreeNode* currNode = q.front();
q.pop();
levelResult.push_back(currNode->val);
if(currNode->left)
q.push(currNode->left);
if(currNode->right)
q.push(currNode->right);
}
if(levelId%2!=0){
reverse(levelResult.begin(), levelResult.end());
traversalResult.push_back(levelResult);
}
else
traversalResult.push_back(levelResult);
levelId++;
}
return traversalResult;
}
};
Time Complexity: O(n), Each node visited once
Space Complexity: O(n), the queue can store all the nodes of the last level.