Zigzag Level Order Traversal in Java: A Simple and Clear Guide
Working with binary trees can be exciting, especially when you encounter traversal problems that require a little twist.
One such problem is Zigzag Level Order Traversal, where you donโt simply traverse each level from left to rightโyou need to alternate directions on each level.
In this post, Iโll walk you through the solution using Java, provide step-by-step explanations, and share some helpful insights to make the concept stick.
๐ Problem Overview
The task is to traverse a binary tree level by level, but the direction switches at each level.
- First level: left to right
- Second level: right to left
- Third level: left to right
- And so onโฆ
This creates a zigzag or spiral-like pattern.
๐ Example
Given the following tree:
1
/ \
2 3
/ \ \
4 5 6
Expected Output:
[
[1],
[3, 2],
[4, 5, 6]
]
๐ก Thought Process
We can approach this using Breadth-First Search (BFS) with a small twist:
- Keep track of whether we should read left-to-right or right-to-left.
- Use a LinkedList to allow quick insertions at both the beginning and end.
- Flip the direction after processing each level.
โ Java Solution
Hereโs a clean and readable Java implementation:
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean isLeftToRight = true;
while (!queue.isEmpty()) {
int levelSize = queue.size();
LinkedList<Integer> levelList = new LinkedList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
if (isLeftToRight) {
levelList.addLast(currentNode.val);
} else {
levelList.addFirst(currentNode.val);
}
if (currentNode.left != null) queue.offer(currentNode.left);
if (currentNode.right != null) queue.offer(currentNode.right);
}
result.add(levelList);
isLeftToRight = !isLeftToRight; // Flip direction for the next level
}
return result;
}
}
๐ Step-by-Step Breakdown
Initialization:
- Use a Queue for standard BFS.
- Set a boolean flag
isLeftToRight
to track the traversal direction.
Processing Each Level:
- For every level, traverse all nodes in the queue.
- Add node values to the front or back of the level list based on the current direction.
Queue Management:
- Always add child nodes to the queue to prepare for the next level.
Switch Direction:
- After finishing a level, simply flip the boolean flag.
๐ Time and Space Complexity
Time Complexity: O(N)
Every node is visited once.Space Complexity: O(N)
The queue and the output list together may hold all nodes.
๐ Quick Takeaways
- Zigzag traversal is just a variation of level order traversal.
- Keeping track of traversal direction is key.
- Picking the right data structure (like
LinkedList
) simplifies the solution.
๐ Related LeetCode Problems
- Binary Tree Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Right Side View
๐ Final Thoughts
This problem is a great example of how small tweaks can make a standard algorithm interesting.
If youโre diving into tree problems, this is a solid pattern to learn and reuse.
Feel free to drop your thoughts, suggestions, or questions!
Also, Iโd love to connect if youโre interested in exploring more DSA problems together. ๐
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.