Binary Tree Zigzag Level Order Traversal

Read a binary tree level by level, switching between left to right and right to left on each new level.

Given the root of a binary tree, return the values of its nodes level by level, in zigzag order. The top level is read left to right, the next one right to left, the one after that left to right again, and so on. Each level's values form one list, and the answer lists those lists from the top level down.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [20, 9], [15, 7]]
Example 2
Input: root = [1]
Output: [[1]]
Solution

The Idea

Think of a tractor ploughing a field. It drives the first row from west to east, turns around, drives the second row from east to west, and keeps turning at the end of every row. A zigzag reading of a tree moves the same way, but its rows are the levels of the tree.

In Example 1, the array [3, 9, 20, null, null, 15, 7] writes the tree down row by row. The top node, 3, is the root. Its children are 9 on the left and 20 on the right. The two nulls say that 9 has no children, and 20 has the children 15 and 7. Nodes at the same distance from the root form a level: level 0 holds 3, level 1 holds 9 and 20, and level 2 holds 15 and 7.

Read straight across, left to right every time, the levels give [3], [9, 20] and [15, 7]. Zigzag order wants level 1 backwards, so the answer is [[3], [20, 9], [15, 7]]. So how do we walk the tree so that every second level comes out reversed?

The walk itself does not have to change. Visit every level left to right, as usual, and change only where each value is written into its level's list. Look at the picture below.

The tree of Example 1 by level. Level 0 holds 3 and its list is [3]. Level 1 is visited 9, then 20, but it goes right to left, so each value is added to the front and the list is [20, 9]. Level 2 goes left to right, adding to the end: [15, 7].

In the row labelled level 1, the visit order is 9, then 20. This level goes right to left, so each value is added to the front of the list. First 9 makes [9], then 20 goes in front of it, which gives [20, 9]. Levels 0 and 2 go left to right, and their values are added to the end.

So the zigzag is only about placement. The walk underneath is the plain level-by-level walk of Level Order Traversal, known as breadth-first search, or BFS, because it covers the whole width of one level before going deeper.

Solution Approach

Turning that idea into code means deciding how to visit one level at a time, where each value goes in its level's list and when to switch direction, and seeing why reversing the visit itself goes wrong.

Visiting one level at a time

How do we visit the nodes level by level? A queue does it, because nodes leave a queue in the order they joined. The queue begins holding just the root. Take a node out, then put its left child and its right child at the back. Children always join behind every node already waiting, so all of level 1 leaves the queue before any node of level 2.

Where does one level end? At the start of each round, the queue holds exactly the nodes of one level. In Example 1, once 3 has left, the queue holds 9 and 20. Its size, 2, says how many nodes to take out before level 2 begins.

Placing each value in the level's list

Where does a value go? On a left-to-right level, at the end of the list. On a right-to-left level, at the front, which reverses that level while it is read. Java's LinkedList keeps its values in a chain of linked cells, and its addLast and addFirst both take the same short time however long the list is. An ArrayList could call add(0, x), but that shifts every value already in the list one place to the right.

As an alternative, every value can be added to the end, and every second list reversed with Collections.reverse once its level is complete. That works too, at the cost of one more pass over those levels.

Switching direction

When does the direction change? Once per level, right after its last node leaves the queue. A boolean named leftToRight starts as true for the root's level and flips at the end of every round.

Reversing the visiting order instead

Would it be simpler to queue the children right before left on alternate levels, so that they leave the queue already reversed? That fixes level 1 but breaks the levels below it. Take the full tree of the numbers 1 to 15: level 0 is 1, level 1 is 2 and 3, level 2 is 4 to 7, and level 3 is 8 to 15.

Level 1 then leaves the queue as 3, 2, so the children of 3 are queued ahead of the children of 2. Level 2 comes out as [6, 7, 4, 5] instead of [4, 5, 6, 7]. The order of each level follows the order of the level above it, so reversing the visit swaps whole branches, not just one level.

Java Solution

The method zigzagLevelOrder works in these steps:

  1. First, create levels, the list of lists to return, and queue, an ArrayDeque used as the queue. If root is not null, add it to queue. An empty tree leaves queue empty, and the method returns an empty levels.
  2. Set leftToRight to true, because the root's level is read left to right.
  3. A while loop runs once per level, as long as queue is not empty. It saves the number of nodes waiting in size and creates level, a new LinkedList for this level's values.
  4. Inside, a for loop takes size nodes out of queue with poll. Each value goes to the end of level with addLast when leftToRight is true, and to the front with addFirst otherwise. The node's left and right children, when they exist, join the back of queue.
  5. After the for loop, add level to levels and flip leftToRight. When queue is finally empty, return levels.

The class also has a small TreeNode class and a build helper that turns the row-by-row array form, with null for a missing child, into a tree. The main method runs both examples, an empty tree, the full tree of the numbers 1 to 15, and a tree in which every node has only a left child.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class ZigzagLevelOrderTraversal {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        boolean leftToRight = true;
        while (!queue.isEmpty()) {
            int size = queue.size();               // nodes on this level
            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);      // same visiting order, reversed placement
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            levels.add(level);
            leftToRight = !leftToRight;            // next level goes the other way
        }
        return levels;
    }

    // Builds a tree from the row-by-row form, where null marks a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = parents.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(zigzagLevelOrder(build(3, 9, 20, null, null, 15, 7)));
        System.out.println(zigzagLevelOrder(build(1)));
        System.out.println(zigzagLevelOrder(build()));
        System.out.println(zigzagLevelOrder(
                build(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)));
        System.out.println(zigzagLevelOrder(build(1, 2, null, 3, null, 4)));
    }
}

Running it prints:

Output
[[3], [20, 9], [15, 7]]
[[1]]
[]
[[1], [3, 2], [4, 5, 6, 7], [15, 14, 13, 12, 11, 10, 9, 8]]
[[1], [2], [3], [4]]

Example 1 gives [[3], [20, 9], [15, 7]], with 20 ahead of 9 on level 1, just as in the picture. The empty tree prints [], because the while loop never runs.

Look at the fourth line, the tree of 1 to 15. Level 2 reads [4, 5, 6, 7], not the [6, 7, 4, 5] that reversing the visiting order produces, and level 3 runs backwards from 15 down to 8. On the last line every level holds a single node, so the direction changes nothing and the result is [[1], [2], [3], [4]].

Complexity

The work is one pass through the tree, with a queue holding the nodes that wait for their turn.

  • Time: O(n), because each of the n nodes joins the queue once, leaves it once, and goes into its level's list with an addFirst or addLast that takes constant time.
  • Space: O(w) besides the output, where w is the largest number of nodes on one level, because the queue holds the rest of one level plus the children already queued from it.