Zigzag Level Order Traversal of Binary Tree

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example: Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

Approach

Use a deque to allow insertion at both ends. For odd-nmubered levels (1-indexed), add nodes to the tail; for even-numbered levels, add nodes to the head.

Solution

  1. Handle edge case: if root is null, return empty list.
  2. Initialize result list res and a queue deque containing root.
  3. While deque is not empty:
    • Create a new linked list tmp for current level.
    • Iterate over current level nodes (size of deque):
      • Poll node from front of deque.
      • If res.size() % 2 == 0 (odd level), add node.val to tmp's tail; else add to head.
      • Add left and right children to deque if not null.
    • Add tmp to res.
  4. Return res.
import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root != null) queue.add(root);
        while (!queue.isEmpty()) {
            LinkedList<Integer> tmp = new LinkedList<>();
            for (int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                if (res.size() % 2 == 0) tmp.addLast(node.val);
                else tmp.addFirst(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            res.add(tmp);
        }
        return res;
    }
}

Complexity Analysis:

  • Time complxeity: O(n), where n is the number of nodes.
  • Space complexity: O(n) for the queue and result.

Tags: java binary tree bfs Deque Level Order Traversal

Posted on Mon, 27 Jul 2026 16:05:55 +0000 by Hypnos