Binary Tree Zigzag Level Order Traversal explained

Binary Tree Zigzag Level Order Traversal is a normal level-by-level breadth-first search where every other row is written right to left. Keep the queue in its usual left-to-right order, and change only how each row is built: append values on left-to-right rows and prepend them, or write them into reversed positions, on the others. Every node is handled once, so it runs in O(n) time.

By Published 7 min read

The task, reworded

Given the root of a binary tree, return a list of rows. Row 0 holds the root. Row 1 holds the root's children, listed from right to left. Row 2 holds the grandchildren from left to right, and the direction keeps alternating. An empty tree returns an empty list.

           8
         /   \
        3     10
       / \      \
      1   6      14
         / \    /
        4   7  13

  [[8], [10, 3], [1, 6, 14], [13, 7, 4]]
A tree drawn for this page, with the zigzag output from the code below

Read the drawing like a snake: 8, then back along the second row (10, 3), forward along the third (1, 6, 14), and back along the fourth (13, 7, 4). Ask whether row 0 should go left to right (the usual convention) and whether an empty tree should return an empty list or something else.

Why interviewers like this variation

It takes a standard breadth-first search and adds one twist, which shows quickly whether a candidate understands what the queue is doing. The common wrong move is to start pushing children right to left on alternate rows. That changes which nodes come out first on the following row and scrambles everything below. The clean answer leaves the traversal alone and changes only the output.

Simple version: level order, then reverse odd rows

Run the usual level order traversal, collecting each row left to right, then reverse rows 1, 3, 5 and so on. It is correct and still O(n) overall, since reversing a row costs its length. It is a fine first answer, and a good test reference. Some interviewers ask you to avoid the separate reverse step, which leads to the versions below.

Build each row in its final order

Process the queue exactly as in plain level order: record how many nodes are in the current row, pop that many, and push their children left then right. Only the destination changes. On a left-to-right row, append each value at the back of the row. On a right-to-left row, add it at the front. A double-ended queue makes adding at the front O(1), so the row is ready the moment the level ends. Then flip the direction flag.

from collections import deque

def zigzag_rows(root):
    rows = []
    if root is None:
        return rows
    queue = deque([root])
    left_to_right = True
    while queue:
        row = deque()
        for _ in range(len(queue)):
            node = queue.popleft()
            if left_to_right:
                row.append(node.val)
            else:
                row.appendleft(node.val)  # build the row backward
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        rows.append(list(row))
        left_to_right = not left_to_right
    return rows
Python: one queue for nodes, one deque per row. O(n) time.

In C++ the same effect comes from sizing the row first. Since you know the row's width before popping, the k-th node popped goes to slot k on a forward row, or slot width - 1 - k on a backward row.

#include <queue>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left = nullptr;
    TreeNode* right = nullptr;
    explicit TreeNode(int v) : val(v) {}
};

vector<vector<int>> zigzagRows(TreeNode* root) {
    vector<vector<int>> rows;
    if (root == nullptr) return rows;
    queue<TreeNode*> q;
    q.push(root);
    bool leftToRight = true;
    while (!q.empty()) {
        int width = q.size();
        vector<int> row(width);
        for (int k = 0; k < width; ++k) {
            TreeNode* node = q.front();
            q.pop();
            // write each value straight into its final slot
            row[leftToRight ? k : width - 1 - k] = node->val;
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
        rows.push_back(row);
        leftToRight = !leftToRight;
    }
    return rows;
}
C++: write each value straight into its mirrored slot.

Rows for the example tree

Queue order is always left to right; only the row direction alternates
RowNodes popped, in queue orderDirectionRow written
08left to right[8]
13, 10right to left[10, 3]
21, 6, 14left to right[1, 6, 14]
34, 7, 13right to left[13, 7, 4]
Queue order is always left to right; only the row direction alternates. Scroll sideways on a small screen.

The two-stack alternative

Another well-known approach keeps two stacks, one for the current row and one for the next. Popping a stack naturally reverses order, so you push children left then right on one kind of row and right then left on the other. It works, but it is easier to get wrong because the push order must change every row. The single queue with a flipping output is simpler to explain.

Complexity

n nodes, widest row w
ApproachTimeExtra space beyond the output
Level order, then reverse odd rowsO(n)O(w) for the queue
Deque per row, or mirrored slotsO(n)O(w)
Two stacksO(n)O(w)
Depth-first with a depth index, reverse at the endO(n)O(h) for recursion
n nodes, widest row w. Scroll sideways on a small screen.

Edge cases

  • Empty tree: return an empty list before creating a queue.
  • A single node: one row holding one value.
  • Rows with one node: the direction does not visibly matter, but the flag must still flip so the next row is correct.
  • Lopsided trees where whole sides are missing: the queue simply has fewer nodes, and the mirrored placement still uses the row's actual width.

Mistakes to avoid

  • Changing the child push order on alternate rows while still using a single queue.
  • Reading the row width inside the loop instead of before it, which mixes rows together as children are added.
  • Flipping the direction flag inside the per-node loop instead of once per row.
  • Calling insert at index 0 on a Python list or unshift on a JavaScript array for every value, which costs O(w) per insert and O(w²) per row on wide trees.

Follow-up questions

  • Return rows bottom-up. Collect rows as usual, then reverse the list of rows at the end.
  • Return only the last value of each row. That is Binary Tree Right Side View.
  • Average or maximum per row. Same skeleton; replace the row list with a running total or running maximum.
  • Do it depth first. Pass the depth down, append to rows[depth], and reverse odd rows at the end.

In your own words

Fictional example

A spoken version of the approach
Candidate
I'll do a standard level order with a queue, taking one full row at a time by noting the queue length first.
Candidate
I won't change the order children go into the queue, because that would scramble the rows below. Instead I'll flip only how I write each row: at the back on even rows and at the front on odd rows, using a deque.
Candidate
Each node is pushed and popped once, so it's linear time, and the queue holds at most one row's worth of nodes plus their children.

Binary Tree Level Order Traversal is the plain version of this walk. Binary Tree Right Side View keeps only one value per row. Binary Tree Inorder Traversal and Flatten Binary Tree to Linked List are depth-first walks, for contrast. All are listed on the coding problems hub.

Rehearsing tree problems with Natively

While practicing on a Mac or Windows PC, you can let Natively read this prompt from a screenshot and ask it why reversing the push order breaks the next row, then compare its explanation with yours. It transcribes the mock session and saves notes, so you can confirm you described the row-width snapshot before coding. More on the AI interview assistant page.

Questions people ask

How do you do a zigzag level order traversal?

Run a normal breadth-first search one level at a time. Keep pushing children left then right, and alternate only how each row is written: append values on even rows and add them at the front on odd rows.

Why not reverse the child push order on alternate levels?

With a single queue, changing the push order changes which nodes come out first on the next level and scrambles every row below. Flip the output row, not the traversal.

What is the complexity of zigzag level order traversal?

O(n) time, since each node is pushed and popped once, and O(w) extra space for the queue, where w is the widest level.

Can zigzag traversal be done with two stacks?

Yes. One stack holds the current level and one the next, and the child push order alternates. It works, but it is easier to get wrong than one queue with a flipping output row.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP