DEV Community

Virendra Jadhav
Virendra Jadhav

Posted on

Zigzag Level Order Traversal in Java: A Simple and Clear Guide

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
Enter fullscreen mode Exit fullscreen mode

Expected Output:

[
  [1],
  [3, 2],
  [4, 5, 6]
]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก 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;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” 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


๐Ÿ™Œ 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.