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

Print the nodes of a binary tree level by level, from top to bottom.

1Reading an organisation chart row by row

Think of the organisation chart that hangs in many offices. The director is in the top row, the managers who report to the director are in the row below, their teams are in the row below that, and so on. Suppose a receptionist must hand out invitations row by row, top row first, each row from left to right. She does not need to understand the whole chart at once. She only needs a waiting list: when she hands an invitation to a person, she writes that person's direct reports at the bottom of her list, and she always serves the name at the top of the list next.

A binary tree is such a chart. Each box is a node, holding a value and links to at most two children, a left child and a right child. The node at the top is the root, and the depth of a node is how many links we follow down from the root to reach it. Printing level by level means printing every node at depth 0, then every node at depth 1, and so on, each level from left to right.

Our example has root 1. Its children are 2 and 3. Node 2 has children 4 and 5, node 3 has only a right child 6, and node 5 has a left child 7. Let us read it by hand, row by row, the way the receptionist would. The top row is 1. The next row is 2 and 3. Below them, from left to right, are 4, 5 and 6. And the bottom row holds 7 alone. So the expected output is [1], [2, 3], [4, 5, 6], [7].

PictureThe example tree and its four levels

Node 1 is the root. Each level is the set of nodes the same number of steps below the root.

  1. 1234567
    level 0
    [1]
    level 1
    [2, 3]
    level 2
    [4, 5, 6]
    level 3
    [7]

    1The answer reads the tree in rows: [1], then [2, 3], then [4, 5, 6], then [7], each row from left to right.

What to assume

Should each level be printed on its own line, or is one flat sequence enough?
We will return one list per level, which covers both.
Within a level, left to right?
Yes.
What should an empty tree give?
An empty result.
And how deep can the tree be?
Perhaps very deep, even one long chain of a hundred thousand nodes, so we should avoid recursion that goes as deep as the tree.

The question looks as if it needs some clever recursion, but it is smaller than it looks. The receptionist's waiting list already contains the whole method, and the only extra care is knowing where one row ends and the next begins.

A careful candidate asks a few questions first. Should each level be printed on its own line, or is one flat sequence enough? We will return one list per level, which covers both. Within a level, left to right? Yes. What should an empty tree give? An empty result. And how deep can the tree be? Perhaps very deep, even one long chain of a hundred thousand nodes, so we should avoid recursion that goes as deep as the tree, because each pending call takes room on the call stack and too many cause a StackOverflowError.

2How to recognise a breadth-first search problem

Most of us learn tree traversals first in their recursive forms, preorder, inorder and postorder, so a beginner naturally reaches for recursion here. Those traversals are depth-first: they go all the way down one branch before coming back for its neighbour, so preorder on our tree visits 1, 2, 4, 5, 7 and only then 3. Node 7 appears before node 3, though it is two rows lower. Depth-first order simply does not match rows.

The clue in the question is the phrase level by level. It asks us to finish everything at one distance from the root before going any further. A second, quieter clue is top to bottom: the first nodes we discover, the ones near the root, must be the first nodes we finish.

That second clue tells us which container to use. A queue is a line where items are served in the order they arrived, first in, first out, like the line at a ticket counter or the receptionist's waiting list. When we take a node from the queue, we add its children at the back, so they wait behind everyone already in line, and everyone already in line is either on the same row or the row above.

The technique this points to is breadth-first search, usually shortened to BFS. Breadth means width, so the name says we spread across the width of the tree, one row at a time, before going deeper. It belongs to the trees family here, but the rule carries much further: whenever a question mentions levels, distance from a starting point, or the fewest steps in a tree or an unweighted graph, think of breadth-first search with a queue.

Some patterns look close but do not fit. A stack, which works like a pile of plates where the last plate on is the first off, gives a depth-first order, so swapping the queue for a stack quietly breaks the answer. Recording each node's depth and sorting by depth would work, but sorting costs O(n log n) for an order the queue gives us for free.

3The honest first attempt, one walk per level

A natural first attempt uses the recursion we already know. We work out the height of the tree, which is the number of levels, and then for each depth d from 0 to height - 1 we walk down from the root and collect the nodes exactly d steps below it. Because each walk visits the left child before the right child, every level comes out from left to right. It is correct, and it is an honest place to start.

Step throughThe brute force walks down from the root again for every level

Nodes the walk passes through are marked as compared; nodes it collects for the level are marked as found.

  1. 1234567
    depth
    0
    collected
    [1]
    visits
    1
    total
    1

    1The walk for depth 0 visits only the root and collects 1. One visit.

  2. 1234567
    depth
    1
    collected
    [2, 3]
    visits
    3
    total
    4

    2The walk for depth 1 starts at the root again, passes through 1 and collects 2 and 3. Three visits.

  3. 1234567
    depth
    2
    collected
    [4, 5, 6]
    visits
    6
    total
    10

    3The walk for depth 2 passes through 1, 2 and 3 once more before it collects 4, 5 and 6. Six visits.

  4. 1234567
    depth
    3
    collected
    [7]
    visits
    7
    total
    17

    4The walk for depth 3 passes through all six upper nodes again to collect the single node 7. That makes seventeen visits for a tree of seven nodes.

Java
// Brute force: for each depth d, walk down from the root and collect the nodes at depth d.
static int height(Node node) {
return node == null ? 0 : 1 + Math.max(height(node.left()), height(node.right()));
}
static void collect(Node node, int depth, List<Integer> out) {
if (node == null) return;
if (depth == 0) { out.add(node.val()); return; } // we have arrived at the level
collect(node.left(), depth - 1, out); // left first keeps the row in order
collect(node.right(), depth - 1, out);
}
static void printLevels(Node root) {
int h = height(root);
for (int d = 0; d < h; d++) {
List<Integer> level = new ArrayList<>();
collect(root, d, level); // a fresh walk from the root every time
System.out.println(level);
}
}

Let us read it in the order it runs. printLevels first calls height, which asks each node for the taller of its two subtrees and adds one for itself; for our tree that is 4. Then, for each depth, it starts a new list and calls collect from the root. collect lowers depth by one at each step down, and when depth reaches 0 it has arrived at the wanted level, so it adds the value and goes no deeper.

Now let us count by hand, as the picture above did. The walk for depth 0 visits one node, the walk for depth 1 visits three, the walk for depth 2 visits six, and the walk for depth 3 visits seven. That is 17 visits for a tree of 7 nodes, plus 7 more for height. The root alone was visited four times.

For a bushy, balanced tree the repeats stay modest, because most nodes sit in the bottom rows. The worst case is a tree that is one long chain, where every level has a single node. There the height is n, and the walk for depth d passes through d nodes, so the total is about 1 + 2 + ... + n, roughly n squared over 2. We write that as O(n squared). The recursion is also as deep as the tree, up to n calls, which is exactly the stack overflow risk we wanted to avoid.

4From walking again to remembering the children

Look at the waste in the picture. During the walk for depth 1, we stood on node 2 and node 3, and we could see their children, 4, 5 and 6, right below them. Those are exactly the nodes the next walk needs. But we did not write them down, so the next walk climbed all the way back to the root to find them again.

So the fix is to write them down, just as the receptionist does. When we finish with a node, we put its children at the back of a queue. We start with the root alone in the queue, and then, while the queue is not empty, we take the node at the front, record its value, and offer its left child and then its right child at the back. Java's ArrayDeque is the usual queue: offer adds at the back and poll removes from the front.

Why does this give the rows in order? Every node of row d is placed in the queue before any node of row d + 1, because row d + 1 nodes are only added while row d nodes are being taken out. And a queue never lets a later arrival overtake an earlier one. So the nodes come out row by row, and within a row from left to right, because each parent offers its left child before its right child and the parents themselves come out from left to right.

That gives the right order, but the question wants each level on its own line, so we must know where one row stops. Here a beginner often asks whether we need to store each node's depth alongside it. We do not. Look at the queue at the very start of a round, before we take anything out. At that moment it holds exactly one complete row and nothing else, because the previous row has all been taken out and none of this row's children have been added yet. So we read size = queue.size() once, at the start of the round, poll exactly size nodes into this level's list, and leave everything we offered during the round for the next one.

The most common mistake is to write the inner loop as for (k = 0; k < queue.size(); k++), reading the size afresh each time. It is tempting because it looks the same. But the queue grows as children are offered, so the loop keeps going and swallows part of the next row into this one. Reading the size once, into a variable, is what keeps the rows apart.

5Watching the queue on the example tree

The picture runs the queue version on our tree, one poll per frame. Nodes waiting in the queue are marked as compared, the node being polled is marked now, and nodes already finished are marked done. The panel shows size for the current round, the level being built, the queue from front to back, and the result so far.

Watch the queue at the start of each round, in frames 3 and 6. Each time it holds exactly one complete row of the tree.

Step throughBreadth-first search on the example tree, one poll at a time

Nodes waiting in the queue are marked as compared, the node being polled is marked now, and finished nodes are marked done.

  1. 1234567
    queue
    [1]
    result
    []

    1Before the loop starts, the queue holds only the root. Nothing has been printed yet.

  2. 1234567
    size
    1
    level
    [1]
    queue
    [2, 3]
    result
    []

    2Round 1 reads size = 1. It polls node 1, adds 1 to the level, and offers its children 2 and 3 at the back of the queue.

  3. 1234567
    size
    2
    queue
    [2, 3]
    result
    [[1]]

    3Round 1 is over, so [1] joins the result. Round 2 reads size = 2, and the queue holds exactly level 1, nodes 2 and 3.

  4. 1234567
    size
    2
    level
    [2]
    queue
    [3, 4, 5]
    result
    [[1]]

    4Round 2 polls node 2 from the front and offers its children 4 and 5 at the back, behind node 3.

  5. 1234567
    size
    2
    level
    [2, 3]
    queue
    [4, 5, 6]
    result
    [[1]]

    5Round 2 polls node 3 and offers its only child, 6. Two polls were made, so the round stops here.

  6. 1234567
    size
    3
    queue
    [4, 5, 6]
    result
    [[1], [2, 3]]

    6[2, 3] joins the result. Round 3 reads size = 3, and the queue holds exactly level 2: nodes 4, 5 and 6.

  7. 1234567
    size
    3
    level
    [4]
    queue
    [5, 6]
    result
    [[1], [2, 3]]

    7Round 3 polls node 4. It has no children, so nothing is offered and the queue shrinks to [5, 6].

  8. 1234567
    size
    3
    level
    [4, 5]
    queue
    [6, 7]
    result
    [[1], [2, 3]]

    8Round 3 polls node 5 and offers its left child 7, which joins the back of the queue behind node 6.

  9. 1234567
    size
    3
    level
    [4, 5, 6]
    queue
    [7]
    result
    [[1], [2, 3]]

    9Round 3 polls node 6, its third poll, and stops. Node 7 is still waiting, but it belongs to the next level, and size made sure we did not take it.

  10. 1234567
    size
    1
    level
    [7]
    queue
    []
    result
    [[1], [2, 3], [4, 5, 6]]

    10[4, 5, 6] joins the result. Round 4 reads size = 1, polls node 7, and finds no children to offer.

  11. 1234567
    queue
    []
    result
    4 levels
    polls
    7

    11[7] joins the result and the queue is empty, so the loop ends. Every node was offered once and polled once.

Let us read the important frames back. In frame 2 we poll node 1 and offer 2 and 3, so after round 1 the queue is [2, 3], exactly level 1, which frame 3 confirms when it reads size = 2. In frames 4 and 5 we poll 2 and 3, and their children 4, 5 and 6 join the back in that left to right order.

Frame 9 is the moment that matters most. After polling node 6, the queue still holds node 7, so a loop that ran until the queue was empty would put 7 into the same row as 4, 5 and 6. But size was 3, we have polled three nodes, and the round stops. Node 7 waits for round 4, which is exactly where it belongs. In the end each node was offered once and polled once, seven polls in all, against seventeen visits for the brute force.

6The complete Java program

Here is the whole program. The tree node is a small record, a class whose fields are fixed when it is made. The method levels returns one list per level, and main prints the example, an empty tree and a single node, with each printed line shown as a comment.

Java
import java.util.*;
public class LevelOrder {
record Node(int val, Node left, Node right) {
Node(int val) { this(val, null, null); }
}
// Breadth-first search: one list of values per level, top to bottom.
static List<List<Integer>> levels(Node root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Deque<Node> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size(); // nodes on the current level
List<Integer> level = new ArrayList<>(size);
for (int k = 0; k < size; k++) {
Node node = queue.poll();
level.add(node.val());
if (node.left() != null) queue.offer(node.left()); // children join the next level
if (node.right() != null) queue.offer(node.right());
}
result.add(level);
}
return result;
}
public static void main(String[] args) {
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
Node root = new Node(1,
new Node(2, new Node(4), new Node(5, new Node(7), null)),
new Node(3, null, new Node(6)));
for (List<Integer> level : levels(root)) System.out.println(level);
// [1]
// [2, 3]
// [4, 5, 6]
// [7]
System.out.println(levels(null)); // []
System.out.println(levels(new Node(9))); // [[9]]
}
}

Let us read levels in the order it runs. It first makes the result list, and if the root is null it returns that empty list at once, before any queue is created. Otherwise it makes an ArrayDeque, offers the root, and starts the outer loop, which runs once per level for as long as some node is waiting.

At the top of each round, size = queue.size() takes the snapshot we worked out: the number of nodes on this level. The inner loop then runs exactly size times. Each time, poll takes the node at the front, its value goes into level, and each child that exists is offered at the back. We check for null before offering, both because a missing child is not a node and because ArrayDeque refuses null values.

When the inner loop finishes, level holds one complete row, so it is added to result, and the queue now holds exactly the next row. When the queue is finally empty, there is no next row, and we return result. So main prints [1], [2, 3], [4, 5, 6] and [7] on four lines, then [] for the empty tree and [[9]] for the single node.

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

Let us count on the example first. Seven nodes were offered once and polled once, fourteen queue operations in all, each taking constant time. For n nodes that is 2n operations plus a constant amount of work per node, so the time is O(n). We cannot do better, because every value must be printed.

The extra space is the queue. On our tree it never held more than three nodes, the width of the widest row. In general the queue holds at most about one full row plus part of the next, so the space is O(w), where w is the largest number of nodes on one level. In a complete tree the bottom row holds about half the nodes, so w can reach n / 2, which is still O(n) in the worst case. The result lists themselves hold all n values, but those are the answer, not extra space.

Comparing the two ways to print the levels
ApproachTimeExtra space
Walk from the root once per levelO(n squared) for a chainO(h) recursion
BFS with a queue and a size snapshotO(n)O(w) queue

Now the edges. An empty tree returns an empty list before the queue is made, so main prints []. A single node gives one round with size 1 and returns [[9]]. A tree that is one long chain gives n rounds of one node each, the queue never holds more than one node, and there is no recursion that could overflow, which is exactly the case where the brute force was worst. A tree where some nodes have only one child, like node 3 and node 5 in our example, needs nothing special, because we offer only the children that exist.

8Follow-up questions

How would you print the levels in zigzag order, left to right and then right to left?

We keep the same queue and the same size snapshot, and add one boolean that flips after every level. The queue itself never changes order, so children are still offered left then right. Only the way we record each level changes: when the flag says right to left, we put each value at the front of the level list instead of the back, for example with addFirst on a LinkedList. For our tree that gives [1], [3, 2], [4, 5, 6], [7].

Can you do this with depth-first search instead?

Yes. We recurse with the current depth as a parameter. When depth equals the number of lists we have so far, this is the first node we have met on that level, so we start a new list. Then we add the value to the list at index depth and recurse into the left child before the right. Each node is visited once, so it is O(n) time, but the recursion is as deep as the tree, which can overflow on a long chain. That is why the queue version is the usual answer.

How would you return only the rightmost node of each level?

That is called the right side view, what you would see standing to the right of the tree. In the size loop, the node polled when k equals size - 1 is the last node of the row, so we record only that one. For our tree that gives 1, 3, 6 and 7. The time and space stay the same.

9Conclusion

We printed a binary tree level by level. Walking down from the root once per level was correct but kept finding the same nodes again, up to O(n squared) for a chain. Keeping each node's children in a queue, and reading the queue's size once at the start of every round, gave each level in turn with every node offered and polled once, in O(n) time and O(w) space. The clue to remember is the phrase level by level, or any talk of distance from a start: it points to breadth-first search with a queue.

What to say in the interviewAbout 90 seconds aloud

Open with

Let me confirm the output first: one list per level, each from left to right, and an empty result for an empty tree. A brute force would compute the height and walk down from the root once for every depth, collecting the nodes at that depth.

Then, if they want more

That works but revisits the top of the tree on every walk, which is quadratic for a chain, and its recursion is as deep as the tree. Since the question is about levels, I will use breadth-first search with a queue. I offer the root.

While the queue is not empty, I read its size once, which is exactly the number of nodes on the current level, because the previous level is gone and none of this level's children have been added. I poll that many nodes, add each value to the level's list, and offer each node's left and right child if it exists.

Then I add the level to the result, and the queue now holds exactly the next level. Reading the size once matters, because the queue grows during the round. Every node is offered and polled once, so it is O(n) time, and the queue holds about one level, so the space is O(width), O(n) in the worst case.

An empty tree returns an empty list, and a long chain is fine because there is no recursion.

About this answer

Last updated
15 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 17 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 the nodes of a binary tree level by level, from top to bottom.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-the-nodes-of-a-binary-tree-level-by-level-from-top-to-bott-e7e0d0/