Scrivio Interview library
TreesTrees and binary search treesReported 22 times · 16 min read · updated 14 November 2026

Print a binary tree level by level in spiral (zigzag) order.

1What spiral order means, seen as a ploughed field

Think of a farmer ploughing a field. He drives the tractor along the first row from left to right. At the end of the row he turns round and drives the next row from right to left, then the next from left to right again, until the field is done. He never jumps across the field; he only changes direction at the end of each row. Zigzag order is exactly the path he takes, with the rows of the field replaced by the rows of a tree.

Let us make the words clear first. A binary tree is a set of boxes called nodes, each holding a value, where each node may point to at most two nodes below it, its left child and its right child. The node at the top, with nothing above it, is the root. A level is one row of the tree as we draw it on paper: the root alone is level 0, its children form level 1, and so on.

Our example has root 1 with children 2 and 3. Node 2 has children 4 and 5, and node 3 has children 6 and 7. One row lower, node 4 has a left child 8 and node 7 has a right child 9, so 8 and 9 sit far apart under different grandparents.

Now let us drive the tractor over it by hand. Level 0 goes left to right and gives [1]. Level 1 goes right to left and gives [3, 2]. Level 2 goes left to right and gives [4, 5, 6, 7]. Level 3 goes right to left and gives [9, 8]. The answer is [[1], [3, 2], [4, 5, 6, 7], [9, 8]]. You have just solved the problem on paper; the rest is teaching a computer to do the same without missing a node.

PictureThe example tree, row by row

Rows 1 and 3 are read from right to left, rows 0 and 2 from left to right.

  1. 123456789
    row 0
    [1]
    row 1
    [3, 2]
    row 2
    [4, 5, 6, 7]
    row 3
    [9, 8]

    1Read row by row, turning at the end of each row like a tractor: [1], then [3, 2], then [4, 5, 6, 7], then [9, 8].

What to assume

Does the first row go left to right?
We assume so, as is usual.
Do we print the rows or return them?
We return a list of rows, since printing is then one line. An empty tree gives an empty list, and repeated values do not matter, because we work with nodes, not values.

The problem is smaller than it looks. A computer does not see rows the way our eye does, so the task splits into two plain jobs: find out which nodes belong to each row, then write every second row backwards. We will take them one at a time.

A careful candidate asks a few questions first. Does the first row go left to right? We assume so, as is usual. Do we print the rows or return them? We return a list of rows, since printing is then one line. An empty tree gives an empty list, and repeated values do not matter, because we work with nodes, not values.

2How to recognise the level order pattern

When a beginner first reads this question, the word tree brings recursion to mind, because most tree code calls itself on the left child and then on the right. That style is called depth-first, since it dives down one branch before coming back up. Try it on our tree in your head: it visits 1, 2, 4, 8, climbs back to 5, then goes over to 3, 6, 7 and 9. The rows come out mixed, since 8 from the bottom row arrives before 3 from the second row. The habit we bring does not hand us rows.

So let us take the clues one at a time. The first is the phrase level by level. The output is grouped by row, so we want a walk that finishes one whole row before it touches the next. Such a walk is called breadth-first search, or BFS. Breadth means width: the walk goes across the tree before it goes deeper.

The second clue is the word zigzag, or spiral. It tells us the direction changes from row to row, and nothing else. The nodes in each row are the same as in an ordinary row-by-row listing; only the order we write them down changes. So we can take a standard method and change one small detail.

Together the clues point to the trees family and the level order pattern. The tool behind it is a queue, which behaves like the line at a ticket counter: people join at the back and are served from the front. If each node we serve sends its children to the back of the line, a whole row is served before the row below it, because every node of a row joined before any of its children. The rule to carry to new problems is that whenever the answer is organised by rows of a tree, such as the average or the rightmost node of each level, we serve the tree one row at a time from a queue, and only what we do with each row changes.

A depth-first walk that carries the row number can also work, and we meet it at the end. A plain BFS that empties the queue in one long run visits nodes in row order, but it cannot tell where one row ends, so it cannot know when to turn the tractor round. We will fix exactly that.

3The brute force, one fresh walk for every row

When a problem is new, a good first move is to build it from pieces we already know, and that first honest attempt is called the brute force. We can walk a tree recursively and we can reverse a list. So we find how many rows the tree has, and for each row number d we walk from the root, collect the nodes d steps below it from left to right, and reverse the list when d is odd. The number of steps below the root is called the depth of a node, and it equals its row number.

Let us do it by hand. For d = 0 we touch only the root and collect [1]. For d = 1 we touch 1, 2 and 3, collect [2, 3], and reverse it to [3, 2]. For d = 2 we pass through 1, 2 and 3 to collect [4, 5, 6, 7]. For d = 3 we touch every node and collect [8, 9], reversed to [9, 8]. The answer is right.

Java
static List<List<Integer>> zigzagBrute(Node root) {
List<List<Integer>> levels = new ArrayList<>();
int h = height(root); // how many rows the tree has
for (int d = 0; d < h; d++) {
List<Integer> level = new ArrayList<>();
collect(root, 0, d, level); // a fresh walk from the root for every row
if (d % 2 == 1) Collections.reverse(level);
levels.add(level);
}
return levels;
}
static void collect(Node n, int depth, int target, List<Integer> out) {
if (n == null) return;
if (depth == target) { out.add(n.val); return; } // deep enough: write it down
collect(n.left, depth + 1, target, out);
collect(n.right, depth + 1, target, out);
}

Now let us count. Finding the height touches all 9 nodes, and the four walks touch 1, 3, 7 and 9 nodes, 29 visits in all for 9 nodes. We counted by running the code with a counter. The root alone was touched five times.

In general, with n nodes and h rows, each of the h walks may touch up to n nodes, so the time is O(n h), read as order n times h. For a tree that is really a long chain, h equals n and the time becomes O(n squared). The extra memory, called the space, is O(h) for the recursion, plus the answer.

The waste is plain. To reach row 3 we pass through rows 0, 1 and 2 again, though we had them in our hands a moment ago. Could one walk hand us every row in turn, touching each node once? It can, and the ticket line is how.

4Getting to one walk that turns at every row

Let us start from the waste and use the ticket line to meet every row in one walk. We put the root in the line. Then, again and again, we serve the node at the front, write down its value, and send its children, left first, to the back. A parent always joins before its children, so every node of row 1 joins before any node of row 2. One walk, and each node is served once.

A beginner rightly asks how we know where a row ends, if the line is one long stream. Here is a trick worth remembering. At the moment a row starts, the line holds exactly that row and nothing else. So we read the length of the line first, keep it in a variable called size, and serve exactly size nodes; their children wait for the next round. On the example the line starts as [1], size 1, and serving 1 adds 2 and 3. Now the line is [2, 3], size 2, exactly row 1.

Why not simply serve until the line is empty? Let us try it and see what we lose. After serving 2 the line is [3, 4, 5], and we would carry on into 4 and 5 as if they belonged to row 1. The tractor would never reach the end of a row, so it would never turn. Reading size at the start of each round draws the boundary.

Now the turn, and the mistake most beginners make. The tempting idea is to add the right child before the left on a reversed row. Row 1 comes out as 3, 2, which looks right. But the line now holds 3 before 2, so 3's children are served before 2's, and row 2 comes out as 6, 7, 4, 5. We ran this version to be sure, and the picture shows the damage.

Step throughThe trap: turning the line round instead of the row

On a reversed row the right child joins the line first. Row 1 looks right, but row 2 is spoiled.

  1. 123456789
    line
    [3, 2]
    row 1
    [3, 2]

    1Row 1 should be reversed, so when we serve the root we add 3 before 2. The line is [3, 2], and row 1 prints as 3, 2, which looks right.

  2. 123456789
    line
    [6, 7, 4, 5]
    row 2 printed
    [6, 7, 4, 5]
    row 2 wanted
    [4, 5, 6, 7]

    2Now the line serves 3 before 2, so 3's children 6 and 7 join before 2's children 4 and 5. Row 2 prints as 6, 7, 4, 5, which is wrong.

So the line has two jobs and we must not mix them. Deciding which nodes come next needs it to run left to right, always. Writing the row down is the only place where direction should matter.

For writing a row we use a deque, short for double-ended queue and said like deck. Think of a bench where we may seat a person at either end. On a left-to-right row each value sits at the back, so the row reads in serving order. On a right-to-left row each value sits at the front, so the last served ends up first: serving 2 and then 3 gives [2], then [3, 2].

Why is this always right? At the start of every round the line holds exactly the current row, in left-to-right order, because the parents were served left to right and each sent its left child first. Back seating then writes the row left to right and front seating right to left. A boolean called leftToRight chooses, and we flip it after every row, the tractor turning at the end of the furrow.

5Watching the line and the rows on the example tree

The picture plays the method on our tree. The node being served is marked as looked at, nodes waiting in the line as compared, and nodes written down as finished. The panel shows the line, the row being written, the direction, and the rows finished so far.

Watch two things. The line always holds nodes in left-to-right order, and only the bench changes direction. The frames worth slowing down for are those of rows 1 and 3, where each value is seated at the front.

Step throughZigzag order on the example tree, one serving at a time

The node being served is marked as looked at, nodes waiting in the line as compared, and served nodes as finished.

  1. 123456789
    line
    [1]
    this row
    -
    direction
    left to right
    rows done
    []

    1We begin with only the root in the line. Nothing has been written down yet, and the first row goes left to right.

  2. 123456789
    line
    [2, 3]
    this row
    [1]
    direction
    left to right
    rows done
    [[1]]

    2Row 0: size is 1, so we serve one node. Node 1 is seated at the back of the row, and its children 2 and 3 join the line.

  3. 123456789
    line
    [3, 4, 5]
    this row
    [2]
    direction
    right to left
    rows done
    [[1]]

    3Row 1 turns round. size is 2. We serve node 2 and seat it at the front, giving [2], while 4 and 5 join the back of the line.

  4. 123456789
    line
    [4, 5, 6, 7]
    this row
    [3, 2]
    direction
    right to left
    rows done
    [[1], [3, 2]]

    4We serve node 3 and seat it at the front, so it lands before 2: [3, 2]. Its children 6 and 7 join the line, after 4 and 5.

  5. 123456789
    line
    [5, 6, 7, 8]
    this row
    [4]
    direction
    left to right
    rows done
    [[1], [3, 2]]

    5Row 2 goes left to right again, and size is 4. Node 4 is served and seated at the back, and its child 8 joins the line.

  6. 123456789
    line
    [7, 8]
    this row
    [4, 5, 6]
    direction
    left to right
    rows done
    [[1], [3, 2]]

    6Nodes 5 and 6 are served next. They have no children, so the line only shrinks, and the row grows at the back to [4, 5, 6].

  7. 123456789
    line
    [8, 9]
    this row
    [4, 5, 6, 7]
    direction
    left to right
    rows done
    [[1], [3, 2], [4, 5, 6, 7]]

    7Node 7 is the fourth and last node of row 2. It is seated at the back, and its right child 9 joins the line behind 8.

  8. 123456789
    line
    [9]
    this row
    [8]
    direction
    right to left
    rows done
    [[1], [3, 2], [4, 5, 6, 7]]

    8Row 3 turns round, and size is 2. Node 8 is served first, as the line always runs left to right, and it is seated at the front.

  9. 123456789
    line
    []
    this row
    [9, 8]
    direction
    right to left
    rows done
    [[1], [3, 2], [4, 5, 6, 7], [9, 8]]

    9Node 9 is served and seated at the front, ahead of 8, so the row reads [9, 8]. Nobody new joined, so the line is empty.

  10. 123456789
    line
    []
    rows done
    [[1], [3, 2], [4, 5, 6, 7], [9, 8]]

    10The line is empty, so the outer loop stops. Every node was served exactly once, and the answer is [[1], [3, 2], [4, 5, 6, 7], [9, 8]].

In the third frame node 2 is seated, giving [2]. In the fourth, node 3 is served after it, because the line runs left to right, yet it sits in front of 2, so the row reads [3, 2]. Meanwhile the line holds 4, 5, 6, 7 in proper order, which is why row 2 comes out right.

In the last row 8 is served before 9, as the line demands, but front seating puts 9 first, giving [9, 8]. Check one thing yourself: at the start of each round the line holds 1, then 2, then 4, then 2 nodes, exactly the sizes of the four rows.

6The complete Java program

Here is the whole program, with a small Node class, the zigzag method, and a main that tries the example tree, a single node and an empty tree. Each comment shows what that line prints.

Java
import java.util.*;
public class ZigzagLevels {
static class Node {
int val;
Node left, right;
Node(int val, Node left, Node right) { this.val = val; this.left = left; this.right = right; }
Node(int val) { this(val, null, null); }
}
// Level by level; even levels left to right, odd levels right to left.
static List<List<Integer>> zigzag(Node root) {
List<List<Integer>> levels = new ArrayList<>();
Deque<Node> queue = new ArrayDeque<>();
if (root != null) queue.add(root);
boolean leftToRight = true;
while (!queue.isEmpty()) {
int size = queue.size(); // how many nodes this level has
Deque<Integer> level = new ArrayDeque<>();
for (int i = 0; i < size; i++) {
Node n = queue.poll();
if (leftToRight) level.addLast(n.val);
else level.addFirst(n.val); // reversed level: put it in front
if (n.left != null) queue.add(n.left);
if (n.right != null) queue.add(n.right);
}
levels.add(new ArrayList<>(level));
leftToRight = !leftToRight; // the next level goes the other way
}
return levels;
}
public static void main(String[] args) {
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
// / \
// 8 9
Node root = new Node(1,
new Node(2, new Node(4, new Node(8), null), new Node(5)),
new Node(3, new Node(6), new Node(7, null, new Node(9))));
System.out.println(zigzag(root)); // [[1], [3, 2], [4, 5, 6, 7], [9, 8]]
System.out.println(zigzag(new Node(5))); // [[5]]
System.out.println(zigzag(null)); // []
}
}

Let us read zigzag in the order it runs. levels is the answer, one inner list per row. queue is the ticket line; an ArrayDeque adds at the back with add and removes from the front with poll. The root goes in only if there is one, so an empty tree leaves the line empty. leftToRight starts as true for row 0.

The outer loop runs once per row. Its first line, int size = queue.size(), freezes the length of the current row before any children join. Then we make a fresh bench, level, for this row.

The inner loop serves exactly size nodes. poll takes the front node. On a left-to-right row addLast seats its value at the back; otherwise addFirst seats it at the front. Then its children join the line, left before right, every time, whatever the direction. That fixed order keeps the next row correct.

After the round, new ArrayList<>(level) copies the bench front to back into levels, and leftToRight = !leftToRight turns the tractor. When the line is empty we return levels, so main prints [[1], [3, 2], [4, 5, 6, 7], [9, 8]], then [[5]], then [].

7How much it costs, and the cases at the edges

On the example, each of the 9 nodes joined the line once, was served once and was seated once: 9 servings against the 29 visits of the brute force. For n nodes that is a few steps per node, so the time is O(n), and no method can do better, since every node must appear in the answer.

The answer holds all n values. The line holds at most one row and part of the next; in our tree never more than 4 nodes, after node 3 was served. In a full tree the bottom row is about half the nodes, so the line can reach n / 2, and the extra space is O(n).

Comparing the ways to print a tree in zigzag order
ApproachTimeExtra space
Brute force: one fresh walk for every rowO(n h), O(n^2) for a chainO(h) for the recursion
Two stacks, one per rowO(n)O(n)
Queue by rows, deque for each rowO(n)O(n)

An empty tree never enters the loop and returns []. A single node is served in one round and gives [[5]]. A long chain has one node per row, so front or back seating gives the same answer. Rows with gaps, like our last row, cause no trouble, because the line holds only real nodes, never empty positions.

8Follow-up questions

How does the two stack solution work?

A stack is a pile of plates, where the last plate put on is the first taken off. We keep one stack for the current row and one for the next. On a left-to-right row we pop each node and push its children onto the other stack left then right; on a right-to-left row, right then left. Because a pile gives things back in reverse, the next row comes off in the opposite direction by itself. It is also O(n) time and space, but the push order is easy to get backwards.

How would you print the rows from the bottom up?

The walk does not change. We serve the tree row by row as before, and add each finished row to the front of the answer instead of the back, or reverse the list of rows at the end. Only where each row is placed changes.

Can this be done with a depth-first walk?

Yes. A recursive method carries the depth with it and creates a bench the first time it reaches a new depth. Because it goes left before right, it meets each row from left to right, so it seats values at the back on even depths and at the front on odd depths. It uses O(h) recursion space, which a very deep chain could overflow.

9Conclusion

We printed a tree in zigzag order by serving it one row at a time from a queue. Reading the queue size at the start of each round draws the boundary between rows, children always join the line left then right, and a deque writes each row from the back or the front, so only the writing turns round. It takes O(n) time and O(n) space. The clue to remember is an answer organised by rows of a tree: serve one row per round from a queue, and change only what you do with each row.

What to say in the interviewAbout 70 seconds aloud

Open with

Let me confirm the setup: the first row goes left to right, I return a list of rows, and an empty tree gives an empty list. A first attempt would collect each depth with a fresh walk from the root and reverse the odd rows, but that is O(n h), O(n squared) for a chain, because it walks the upper rows again and again.

Then, if they want more

Since the output is organised by rows, I will use breadth-first search with a queue. At the start of each round I read the queue size, which is exactly the number of nodes in the current row, and I serve that many nodes, adding their children left then right.

I do not change the order children join the queue, because that would spoil the next row. Instead I collect each row in a deque: on left-to-right rows I add at the back, on right-to-left rows at the front, and I flip a boolean after every row.

Each node is queued and served once, so it is O(n) time, and the queue plus the answer is O(n) space.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 22 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Print a binary tree level by level in spiral (zigzag) order.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-a-binary-tree-level-by-level-in-spiral-zigzag-order-80e0a7/