Algo-Sim › Binary Trees & BST
Binary Tree Zigzag Level Order Traversal
Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Level-order BFS that fills each level list from the back, then from the front, alternating, while the queue order never changes.
Problem
Given the root of a binary tree, return its values level by level, where the first level reads left to right, the next right to left, and so on, alternating.
Constraints
- 0 ≤ number of nodes ≤ 2000
- -100 ≤ Node.val ≤ 100
Edge cases to test
- Empty tree
- One node
- Uneven levels
Follow-up questions
- Why fill the level from both ends instead of reversing?
- Writing into a deque (or by index from the back) avoids a separate reverse pass, though both are O(n).
- What is the two-stack version?
- Alternate between two stacks, pushing children left-first on one level and right-first on the next.
Solution
Java
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> levels = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
if (root != null) queue.offer(root);
boolean leftToRight = true;
while (!queue.isEmpty()) {
int size = queue.size();
LinkedList<Integer> level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (leftToRight) level.addLast(node.val);
else level.addFirst(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
levels.add(level);
leftToRight = !leftToRight;
}
return levels;
}Python
from collections import deque
def zigzag_level_order(root):
levels = []
queue = deque([root] if root else [])
left_to_right = True
while queue:
level = deque()
for _ in range(len(queue)):
node = queue.popleft()
if left_to_right:
level.append(node.val)
else:
level.appendleft(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(list(level))
left_to_right = not left_to_right
return levelsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> levels = {};
deque<TreeNode *> queue = {};
if (root != nullptr)
queue.push_back(root);
bool leftToRight = true;
while (!queue.empty()) {
int size = int(queue.size());
deque<int> level = {};
for (int i = 0; i < size; i++) {
TreeNode *node = queue.front();
queue.pop_front();
if (leftToRight)
level.push_back(node->val);
else
level.push_front(node->val);
if (node->left != nullptr)
queue.push_back(node->left);
if (node->right != nullptr)
queue.push_back(node->right);
}
levels.push_back(vector<int>(level.begin(), level.end()));
leftToRight = !leftToRight;
}
return levels;
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)