Binary Tree Zigzag Level Order Traversal
Binary Tree Zigzag Level Order Traversal is a medium trees & bst problem solved with the traversals pattern.
The best approach, fill each level in place (deque per level), runs in O(n) time and O(w) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from level order, reverse odd levels up.
Problem
Return the level order traversal of a binary tree in zigzag order: the first level left to right, the next right to left, and so on.
Examples
Example 1
- Input
root = [3, 9, 20, null, null, 15, 7]- Output
[[3], [20, 9], [15, 7]]
Example 2
- Input
root = [1, 2, 3, 4, null, null, 5]- Output
[[1], [3, 2], [4, 5]]
Constraints
- The tree has
0to2000nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Level order, reverse odd levels | O(n) | O(w) |
| Fill each level in place (deque per level) | O(n) | O(w) |
1Level order, reverse odd levels
O(n)O(w)Run normal BFS and reverse every second level's list.
- BFS by level; if the level index is odd, Collections.reverse(level).
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
if (root == null) return out;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
List<Integer> level = new ArrayList<>();
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
level.add(n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
if (out.size() % 2 == 1) Collections.reverse(level);
out.add(level);
}
return out;
}
}class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
out: List[List[int]] = []
if root is None:
return out
q = deque([root])
while q:
level = []
for _ in range(len(q)):
n = q.popleft()
level.append(n.val)
if n.left is not None:
q.append(n.left)
if n.right is not None:
q.append(n.right)
if len(out) % 2 == 1:
level.reverse()
out.append(level)
return outclass Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> out;
if (root == nullptr) return out;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> level;
for (int i = q.size(); i > 0; i--) {
TreeNode* n = q.front(); q.pop();
level.push_back(n->val);
if (n->left != nullptr) q.push(n->left);
if (n->right != nullptr) q.push(n->right);
}
if (out.size() % 2 == 1) reverse(level.begin(), level.end());
out.push_back(level);
}
return out;
}
};function zigzagLevelOrder(root) {
const out = [];
if (root === null) return out;
let q = [root];
while (q.length > 0) {
const level = [];
const next = [];
for (const n of q) {
level.push(n.val);
if (n.left !== null) next.push(n.left);
if (n.right !== null) next.push(n.right);
}
q = next;
if (out.length % 2 === 1) level.reverse();
out.push(level);
}
return out;
}2Fill each level in place (deque per level)
O(n)O(w)Know the level size in advance, so put each value directly at index i (left to right) or size - 1 - i (right to left). No reverse step.
- size = q.size(); Integer[] level = new Integer[size].
- For the i-th polled node: idx = leftToRight ? i : size - 1 - i.
- Flip leftToRight after each level.
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
if (root == null) return out;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
boolean leftToRight = true;
while (!q.isEmpty()) {
int size = q.size();
Integer[] level = new Integer[size];
for (int i = 0; i < size; i++) {
TreeNode n = q.poll();
level[leftToRight ? i : size - 1 - i] = n.val;
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
out.add(Arrays.asList(level));
leftToRight = !leftToRight;
}
return out;
}
}class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
out: List[List[int]] = []
if root is None:
return out
q = deque([root])
left_to_right = True
while q:
size = len(q)
level = [0] * size
for i in range(size):
n = q.popleft()
level[i if left_to_right else size - 1 - i] = n.val
if n.left is not None:
q.append(n.left)
if n.right is not None:
q.append(n.right)
out.append(level)
left_to_right = not left_to_right
return outclass Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> out;
if (root == nullptr) return out;
queue<TreeNode*> q;
q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector<int> level(size);
for (int i = 0; i < size; i++) {
TreeNode* n = q.front(); q.pop();
level[leftToRight ? i : size - 1 - i] = n->val;
if (n->left != nullptr) q.push(n->left);
if (n->right != nullptr) q.push(n->right);
}
out.push_back(level);
leftToRight = !leftToRight;
}
return out;
}
};function zigzagLevelOrder(root) {
const out = [];
if (root === null) return out;
let q = [root];
let leftToRight = true;
while (q.length > 0) {
const size = q.length;
const level = new Array(size);
const next = [];
for (let i = 0; i < size; i++) {
const n = q[i];
level[leftToRight ? i : size - 1 - i] = n.val;
if (n.left !== null) next.push(n.left);
if (n.right !== null) next.push(n.right);
}
q = next;
out.push(level);
leftToRight = !leftToRight;
}
return out;
}Edge cases to test
- Empty tree
- A single path
Hints
Hint 1
Do a normal level order, but write each level's values into the list from the front on odd levels.
FAQ
What is the best time complexity for Binary Tree Zigzag Level Order Traversal?
Fill each level in place (deque per level) runs in O(n) time and O(w) extra space.
Which pattern does Binary Tree Zigzag Level Order Traversal use?
It is a trees & bst problem that uses the traversals pattern. Other problems with the same pattern: Binary Tree Level Order Traversal, Binary Tree Level Order Traversal II, Populating Next Right Pointers in Each Node.
Is there a brute force solution for Binary Tree Zigzag Level Order Traversal?
Yes. Level order, reverse odd levels takes O(n) time and O(w) space. Run normal BFS and reverse every second level's list.
Which edge cases should I test for Binary Tree Zigzag Level Order Traversal?
Empty tree; A single path.