Binary Tree Zigzag Level Order Traversal
Pattern: Level order BFS
Level order, but every other level is read right to left. Keep the queue in normal left-to-right order and only reverse where the values are written.
The problem
Return the values level by level, alternating left to right and right to left, starting left to right.
[3, 9, 20, null, null, 15, 7] gives [[3], [20, 9], [15, 7]]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- How is this different from level order?
- Do you need to change the order children are added?
- How do you write a level backwards cheaply?
Hints
Brute force, and why it fails
Two stacks, one per direction: also O(n) but easier to get wrong.
The key insight
The set of nodes on each level does not depend on the direction, so only the writing order needs to change.
Dry run
| queue | 3 |
|---|
root = [3, 9, 20, null, null, 15, 7]. The queue starts with 3: one node on level 0.
Step 1 of 4
The plan
queue = [root]
while queue:
size = len(queue); level = []
repeat size times: n = pop front; level += n; push n's children
record level
reverse the level when its index is odd
Complexity
- Time
O(n)- Space
O(w)
The same as level order.
Edge cases
- Empty tree.
- One node.
- A chain.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
Queue<TreeNode> q = new ArrayDeque<>();
if (root != null) q.add(root);
boolean leftToRight = true;
while (!q.isEmpty()) {
int size = q.size();
LinkedList<Integer> level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
if (leftToRight) level.addLast(node.val); // the queue is always left to right;
else level.addFirst(node.val); // only where we write changes
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
out.add(level);
leftToRight = !leftToRight;
}
return out;
}
}C++
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> out;
queue<TreeNode*> q;
if (root != NULL) q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = static_cast<int>(q.size());
vector<int> level(size);
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
level[leftToRight ? i : size - 1 - i] = node->val; // only where we write changes
if (node->left != NULL) q.push(node->left);
if (node->right != NULL) q.push(node->right);
}
out.push_back(level);
leftToRight = !leftToRight;
}
return out;
}
};Python
from collections import deque
class Solution:
def zigzagLevelOrder(self, root) -> list[list[int]]:
out, q, left_to_right = [], deque([root] if root else []), True
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
out.append(level if left_to_right else level[::-1]) # the queue is left to right; flip every other level
left_to_right = not left_to_right
return outCommon mistakes
- Changing the order children are pushed, which breaks the levels below.
- Starting right to left.