Zigzag level order traversal

Breadth-first, but alternate the reading direction of every level, left-to-right then right-to-left.

Time O(n)Space O(w)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Run an ordinary level-order BFS with a queue, but keep a flag that flips after every level. On a left-to-right level, place each dequeued node at the next free index; on a right-to-left level, place it counting down from the end instead. Enqueueing children always happens in the same left-then-right order; only where each value lands in the level's array changes.

Code

public static List<List<int>> ZigzagLevelOrder(TreeNode root) {
    var result = new List<List<int>>();
    var queue = new Queue<TreeNode>();
    queue.Enqueue(root);
    bool leftToRight = true;
    while (queue.Count > 0) {
        int count = queue.Count;
        var level = new int[count];
        for (int i = 0; i < count; i++) {
            TreeNode node = queue.Dequeue();
            int idx = leftToRight ? i : count - 1 - i;
            level[idx] = node.val;
            if (node.left != null) queue.Enqueue(node.left);
            if (node.right != null) queue.Enqueue(node.right);
        }
        result.Add(level.ToList());
        leftToRight = !leftToRight;
    }
    return result;
}
static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    Queue<TreeNode> queue = new ArrayDeque<>();
    queue.offer(root);
    boolean leftToRight = true;
    while (!queue.isEmpty()) {
        int count = queue.size();
        Integer[] level = new Integer[count];
        for (int i = 0; i < count; i++) {
            TreeNode node = queue.poll();
            int idx = leftToRight ? i : count - 1 - i;
            level[idx] = node.val;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        result.add(new ArrayList<>(Arrays.asList(level)));
        leftToRight = !leftToRight;
    }
    return result;
}
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int>> result;
    queue<TreeNode*> q;
    q.push(root);
    bool leftToRight = true;
    while (!q.empty()) {
        int count = (int)q.size();
        vector<int> level(count);
        for (int i = 0; i < count; i++) {
            TreeNode* node = q.front(); q.pop();
            int idx = leftToRight ? i : count - 1 - i;
            level[idx] = node->val;
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
        result.push_back(level);
        leftToRight = !leftToRight;
    }
    return result;
}
from collections import deque

def zigzag_level_order(root: TreeNode) -> list[list[int]]:
    result = []
    queue = deque()
    queue.append(root)
    left_to_right = True
    while queue:
        count = len(queue)
        level = [0] * count
        for i in range(count):
            node = queue.popleft()
            idx = i if left_to_right else count - 1 - i
            level[idx] = node.val
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
        result.append(level)
        left_to_right = not left_to_right
    return result

Tips

In the .NET library

This is plain level order traversal with one extra piece of bookkeeping (the alternating flag), proof that fiddly-looking output requirements rarely need a different traversal, just different handling of the same visit order.