Binary Tree Zigzag Level Order Traversal

BFS level order with alternating direction per depth — reverse on odd levels.

Medium
Time O(n) Space O(n)
LeetCode
4 min read
tree bfs queue

Problem#

Given a binary tree, return its level-order traversal but flip the direction on every other depth: level 0 left-to-right, level 1 right-to-left, level 2 left-to-right, and so on.

Examples#

  • [3,9,20,null,null,15,7][[3],[20,9],[15,7]]
  • [1][[1]]

Constraints#

  • 0 <= n <= 2000, -100 <= Node.val <= 100.

Hints#

Hint
Do plain BFS and only reverse the level buffer when the depth is odd.

Approach#

Standard size-snapshot BFS; keep a depth counter and reverse the per-level vector when the level index is odd. Using a deque for output and inserting at either end is an equivalent micro-optimization.

Solution#

Binary Tree Zigzag Level Order Traversal
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root) return ans;
queue<TreeNode*> q;
q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int sz = q.size();
vector<int> level(sz);
for (int i = 0; i < sz; ++i) {
TreeNode* cur = q.front(); q.pop();
int idx = leftToRight ? i : sz - 1 - i;
level[idx] = cur->val;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
ans.push_back(std::move(level));
leftToRight = !leftToRight;
}
return ans;
}
};

Editorial#

Writing into a pre-sized vector at index sz - 1 - i on reversed levels is cheaper than appending and reversing, and avoids the O(level) reverse cost. BFS order itself never changes — only the output placement does.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.