Binary Tree Zigzag Level Order Traversal
BFS level order with alternating direction per depth — reverse on odd levels.
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#
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; }};func zigzagLevelOrder(root *TreeNode) [][]int { ans := [][]int{} if root == nil { return ans } queue := []*TreeNode{root} leftToRight := true for len(queue) > 0 { sz := len(queue) level := make([]int, sz) for i := 0; i < sz; i++ { cur := queue[0] queue = queue[1:] idx := i if !leftToRight { idx = sz - 1 - i } level[idx] = cur.Val if cur.Left != nil { queue = append(queue, cur.Left) } if cur.Right != nil { queue = append(queue, cur.Right) } } ans = append(ans, level) leftToRight = !leftToRight } return ans}from collections import dequefrom typing import List, Optional
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans: List[List[int]] = [] if not root: return ans q = deque([root]) left_to_right = True while q: sz = len(q) level = [0] * sz for i in range(sz): cur = q.popleft() idx = i if left_to_right else sz - 1 - i level[idx] = cur.val if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) ans.append(level) left_to_right = not left_to_right return ansvar zigzagLevelOrder = function(root) { const ans = []; if (!root) return ans; const q = [root]; let leftToRight = true; while (q.length > 0) { const sz = q.length; const level = new Array(sz); for (let i = 0; i < sz; i++) { const cur = q.shift(); const 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(level); leftToRight = !leftToRight; } return ans;};class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); if (root == null) return ans; Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); boolean leftToRight = true; while (!q.isEmpty()) { int sz = q.size(); Integer[] level = new Integer[sz]; for (int i = 0; i < sz; i++) { TreeNode cur = q.poll(); int idx = leftToRight ? i : sz - 1 - i; level[idx] = cur.val; if (cur.left != null) q.offer(cur.left); if (cur.right != null) q.offer(cur.right); } ans.add(Arrays.asList(level)); leftToRight = !leftToRight; } return ans; }}function zigzagLevelOrder(root: TreeNode | null): number[][] { const ans: number[][] = []; if (!root) return ans; const q: TreeNode[] = [root]; let leftToRight = true; while (q.length > 0) { const sz = q.length; const level: number[] = new Array(sz); for (let i = 0; i < sz; i++) { const cur = q.shift()!; const 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(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#
Related#