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

Print a binary tree column by column, in vertical order.

1What printing a tree column by column means

Think of a cinema seen from above. Every seat has a row, counted from the screen, and a column, counted left or right from the centre aisle. Now imagine the people in the cinema are the nodes of a tree. The root sits in the front row, in the centre column, which we call column 0. Each child sits one row further back. A left child sits one column to the left of its parent, and a right child one column to the right.

Printing the tree in vertical order means walking along the columns from the leftmost to the rightmost, and in each column naming the people from the front row to the back. Nothing else is asked. It feels harder than it is because a tree is usually drawn to show parents and children, not columns. Once we have written a column number next to each node, the question becomes a simple sorting of people into columns.

Let us number our example tree by hand. The root is 1, its children are 2 and 3, and the grandchildren are 4 and 5 under 2, and 6 and 7 under 3. The root 1 is in column 0. Node 2 is its left child, so it is in column 0 - 1 = -1, and node 3 is in column 0 + 1 = 1. Node 4, left of 2, is in column -2. Node 5, right of 2, is in column -1 + 1 = 0. Node 6, left of 3, is in column 1 - 1 = 0. Node 7 is in column 2.

So three people share column 0: 1 in the front row, and 5 and 6 together in the third row. Reading columns -2 to 2, the answer is [[4], [2], [1, 5, 6], [3], [7]].

PictureThe example tree and its columns

Each node's column: the root is 0, a left child is one less than its parent, a right child one more. Column 0 is highlighted.

  1. 1col 02col -13col 14col -2567col 2
    column -2
    4
    column -1
    2
    column 0
    1, 5, 6
    column 1
    3
    column 2
    7

    1Root 1 is in column 0. 2 and 3 are in columns -1 and 1. 5 and 6 come back to column 0, so column 0 holds 1, 5 and 6.

What to assume

When two nodes share both the row and the column, like 5 and 6, which comes first?
We assume left to right, as they appear in the row, so 5 before 6.
Do we print or return the columns?
We return a list of lists.
What about an empty tree?
We return an empty list.
And how large can the tree be?
Perhaps 100,000 nodes, possibly one long chain, so we would like to avoid deep recursion.

A careful candidate asks a few questions first. When two nodes share both the row and the column, like 5 and 6, which comes first? We assume left to right, as they appear in the row, so 5 before 6; a stricter variant sorts them by value, and the follow-up questions cover it. Do we print or return the columns? We return a list of lists. What about an empty tree? We return an empty list. And how large can the tree be? Perhaps 100,000 nodes, possibly one long chain, so we would like to avoid deep recursion.

2How to spot the pattern in a column question

On a first reading, a beginner often sees the word print and starts a familiar recursive walk, printing nodes as they come. Very soon it is clear that the nodes of one column are spread all over the tree, and that printing as we go cannot produce columns. That moment of confusion is useful. It tells us we must first collect the nodes into groups and only then print.

The first clue is the word column. A node's column is not stored anywhere in the tree; it depends on the path from the root. When a tree question talks about a position that depends on the path, the general move is to carry that position down with each node as we walk: the child's value is the parent's value plus or minus one.

The second clue is the phrase top to bottom inside each column. Top to bottom is the order of rows, and the walk that visits a tree row by row is called breadth-first search, or BFS. BFS keeps a queue, like a line at a counter: we take a node from the front, deal with it, and put its children at the back. Because children always join the line behind everyone already waiting, a whole row leaves the line before the next row begins.

The third clue is from leftmost to rightmost. The groups themselves must come out in order of their column numbers, so we need to know the smallest and largest column at the end.

Together the clues place the problem in the trees family, in the group of tree traversals that carry extra information with each node. The rule to carry to new problems is this: when a tree question groups nodes by a position, carry the position with each node, and choose the walk whose visiting order matches the order the answer needs. Here that walk is BFS, and the groups live in a map from column number to list.

Two neighbours look similar but do not fit. Plain level order traversal also uses BFS, but it groups by row, not by column. A recursive depth-first walk can carry the column too, but it visits the whole left side before the right, so it can meet a deep node before a shallow one in the same column, as we will see.

3The honest first attempt, one walk for every column

The most natural first plan treats each column as a separate small question. First we walk the tree once just to find the leftmost and rightmost columns. Then, for each column from left to right, we walk the whole tree again in level order and keep only the nodes that belong to that column. This is the brute force, the plain approach with no cleverness. It is clearly correct, and level order inside each walk keeps every column top to bottom.

By hand on our tree, the first walk finds columns -2 to 2. The walk for column -2 visits all seven nodes and keeps only 4. The walk for column -1 visits all seven again and keeps only 2. Column 0 keeps 1, 5 and 6, column 1 keeps 3, and column 2 keeps 7.

Step throughThe first attempt walks the whole tree once per column

In each pass, the nodes kept are highlighted and the nodes visited only to be thrown away are dimmed.

  1. 1234567
    looking for
    column -2
    kept
    4
    visits so far
    7

    1Pass 1 walks all 7 nodes to collect column -2. It keeps 4 and throws the other nodes away.

  2. 1234567
    looking for
    column -1
    kept
    2
    visits so far
    14

    2Pass 2 walks all 7 nodes to collect column -1. It keeps 2 and throws the other nodes away.

  3. 1234567
    looking for
    column 0
    kept
    1, 5, 6
    visits so far
    21

    3Pass 3 walks all 7 nodes to collect column 0. It keeps 1, 5, 6 and throws the other nodes away.

  4. 1234567
    looking for
    column 1
    kept
    3
    visits so far
    28

    4Pass 4 walks all 7 nodes to collect column 1. It keeps 3 and throws the other nodes away.

  5. 1234567
    looking for
    column 2
    kept
    7
    visits so far
    35

    5Pass 5 walks all 7 nodes to collect column 2. It keeps 7 and throws the other nodes away.

Java
static int minCol, maxCol;
static List<List<Integer>> verticalOrderSlow(Node root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
minCol = 0; maxCol = 0;
findRange(root, 0); // first pass: how wide is the tree?
for (int c = minCol; c <= maxCol; c++) {
result.add(collectColumn(root, c)); // one full walk per column
}
return result;
}
static void findRange(Node n, int col) {
if (n == null) return;
minCol = Math.min(minCol, col);
maxCol = Math.max(maxCol, col);
findRange(n.left(), col - 1);
findRange(n.right(), col + 1);
}
static List<Integer> collectColumn(Node root, int target) { // level order keeps top to bottom
List<Integer> out = new ArrayList<>();
Deque<Item> queue = new ArrayDeque<>(List.of(new Item(root, 0)));
while (!queue.isEmpty()) {
Item it = queue.poll();
if (it.col() == target) out.add(it.node().val());
if (it.node().left() != null) queue.offer(new Item(it.node().left(), it.col() - 1));
if (it.node().right() != null) queue.offer(new Item(it.node().right(), it.col() + 1));
}
return out;
}

Let us count. Five columns times seven nodes is 35 visits, plus 7 for finding the range, to place 7 values. In general, with n nodes and w columns, the cost is about n times w visits, written O(n x w). A balanced tree is not very wide, but a tree that leans entirely one way, a chain of n nodes, has n columns, so the cost grows to O(n^2), which for 100,000 nodes is ten billion visits. The queue needs O(n) space.

The picture shows where that time goes. In every pass, most of the tree is dimmed: we visited those nodes, worked out their columns, and threw them away. Yet a node's column never changes from one pass to the next. Every pass recomputes exactly what the previous pass already knew.

4From one walk per column to one walk in all

The waste suggests the fix. Since each node's column is fixed, we should compute it once and drop the node straight into its column's group. For the groups we use a HashMap, which works like the index at the back of a book: we look up a column number and find its list of values. Each time we take a node out of the queue, we append its value to the list for its column, creating the list the first time we see that column.

To carry the column, each entry in the queue is a pair, a node and its column. The root goes in as 1 with column 0. When we take out a pair, we put its left child in with column - 1 and its right child with column + 1. So the column travels down the tree for free.

Now the beginner's question. A recursive preorder walk carries the column just as easily and is shorter, so why insist on BFS? Let us try preorder on a tree where it matters. Take root 1, with 2 on the left and 3 on the right, give 2 a right child 5, and give 5 a right child 8. Node 3 is in column 1, one row down, and node 8 is also in column 1, but three rows down. Preorder finishes everything under 2 before it even looks at 3, so it visits 1, 2, 5, 8 and then 3, and column 1 is filled as [8, 3]. That is bottom first, which is wrong.

Step throughWhy a depth-first walk gets the order wrong

Node 8 sits three rows down in column 1, and node 3 sits one row down in the same column.

  1. 12358col 1
    visit order
    1, 2, 5, 8, 3
    column 1 gets
    [8, 3], wrong

    1A preorder walk finishes the whole left side first: 1, 2, 5, 8, and only then 3. So column 1 is filled as [8, 3], bottom first.

  2. 123col 158
    visit order
    1, 2, 3, 5, 8
    column 1 gets
    [3, 8], right

    2A level-order walk takes row 1 before row 3, so 3 comes out before 8 and column 1 is filled as [3, 8], top first.

BFS cannot make that mistake. It takes every node of row 1 out of the queue before any node of row 2, and so on down, so a higher node always reaches its column's list before a lower one. Within one row, the queue holds the nodes from left to right, because each parent queued its left child before its right child and the parents themselves came out left to right. So every column list is built top to bottom and left to right, with no sorting at all.

That leaves the order of the columns themselves. We could keep the map sorted, but there is a simpler observation. Every child is exactly one column away from its parent, so the columns have no gaps: if the leftmost is -2 and the rightmost is 2, then -1, 0 and 1 each hold at least one node. So we track the smallest column, minCol, and the largest, maxCol, during the walk, and at the end read the map from minCol to maxCol.

5Watching the walk fill the columns on our tree

The picture runs the single BFS on our seven-node tree. In each frame, the node marked now has just left the queue, and the label beside it shows its column. Nodes still waiting in the queue are marked as compared, and finished nodes are marked done. The panel shows the queue, written as value and column, the map of columns so far, and the smallest and largest columns seen.

Watch column 0 in particular. It is started by the root in the second frame and is not touched again until the third row is being taken out of the queue.

Step throughOne breadth-first walk that fills every column

The node marked now has just left the queue, and the label beside it is its column. Nodes waiting in the queue are marked as compared; finished nodes are marked done.

  1. 1234567
    queue
    1(0)
    columns
    none yet
    min, max
    0, 0

    1The queue starts with the root and its column, 1 at column 0. Nothing has been placed in any column yet.

  2. 1col 0234567
    taken out
    1 at column 0
    queue
    2(-1) 3(1)
    columns
    0:[1]
    min, max
    0, 0

    2We take 1 out of the queue with column 0 and start the list for column 0. Its children join the back of the queue: 2 with column -1, 3 with column 1.

  3. 12col -134567
    taken out
    2 at column -1
    queue
    3(1) 4(-2) 5(0)
    columns
    -1:[2] 0:[1]
    min, max
    -1, 0

    3Next out is 2, column -1, so column -1 gets [2]. Its children join the queue: 4 one step left at -2, and 5 one step right, back at 0.

  4. 123col 14567
    taken out
    3 at column 1
    queue
    4(-2) 5(0) 6(0) 7(2)
    columns
    -1:[2] 0:[1] 1:[3]
    min, max
    -1, 1

    4Next out is 3, column 1. Its children 6 and 7 join the queue with columns 0 and 2. The whole second row has now been taken out.

  5. 1234col -2567
    taken out
    4 at column -2
    queue
    5(0) 6(0) 7(2)
    columns
    -2:[4] -1:[2] 0:[1] 1:[3]
    min, max
    -2, 1

    5Now the third row starts. 4 comes out with column -2, the leftmost column so far, so min becomes -2. It has no children.

  6. 12345col 067
    taken out
    5 at column 0
    queue
    6(0) 7(2)
    columns
    -2:[4] -1:[2] 0:[1,5] 1:[3]
    min, max
    -2, 1

    65 comes out with column 0, so it is appended after 1. Column 0 reads [1, 5], top to bottom, without any sorting.

  7. 123456col 07
    taken out
    6 at column 0
    queue
    7(2)
    columns
    -2:[4] -1:[2] 0:[1,5,6] 1:[3]
    min, max
    -2, 1

    76 also has column 0 and comes out after 5, because 5 was queued first. Column 0 reads [1, 5, 6], left to right within the row.

  8. 1234567col 2
    taken out
    7 at column 2
    queue
    empty
    columns
    -2:[4] -1:[2] 0:[1,5,6] 1:[3] 2:[7]
    min, max
    -2, 2

    87 comes out last with column 2, and max becomes 2. The queue is empty, so the walk is over.

  9. 1234567
    read
    columns -2, -1, 0, 1, 2
    result
    [[4], [2], [1, 5, 6], [3], [7]]

    9We read the map from min to max, columns -2 to 2, and get [[4], [2], [1, 5, 6], [3], [7]], the answer we worked by hand.

Let us read the important frames back. After 1 comes out, the queue holds 2(-1) and 3(1), the whole second row. After 2 and 3 come out, the queue holds 4(-2), 5(0), 6(0) and 7(2), the whole third row in left-to-right order. This is the row-by-row promise of BFS made visible.

Then 5 comes out and joins column 0 behind 1, and 6 follows it, because 5 was queued first, by 2, which came out before 3. Column 0 reads [1, 5, 6] without a single comparison. Meanwhile min moved to -2 when 4 came out and max moved to 2 when 7 came out, so the last frame reads exactly five columns, -2 to 2.

6The complete Java program

Here is the full class. It uses a record for the tree node and another record, Item, for the pair of a node and its column that travels through the queue. main runs our tree, a smaller tree where a deeper node shares the root's column, a single node, and an empty tree.

Java
import java.util.*;
public class VerticalOrder {
record Node(int val, Node left, Node right) {
Node(int val) { this(val, null, null); }
}
record Item(Node node, int col) {}
// Columns from left to right; inside a column, top to bottom and left to right.
static List<List<Integer>> verticalOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Map<Integer, List<Integer>> columns = new HashMap<>();
int minCol = 0, maxCol = 0;
Deque<Item> queue = new ArrayDeque<>();
queue.offer(new Item(root, 0));
while (!queue.isEmpty()) { // BFS: upper rows come out first
Item it = queue.poll();
columns.computeIfAbsent(it.col(), c -> new ArrayList<>()).add(it.node().val());
minCol = Math.min(minCol, it.col());
maxCol = Math.max(maxCol, it.col());
if (it.node().left() != null) queue.offer(new Item(it.node().left(), it.col() - 1));
if (it.node().right() != null) queue.offer(new Item(it.node().right(), it.col() + 1));
}
for (int c = minCol; c <= maxCol; c++) result.add(columns.get(c)); // columns are contiguous
return result;
}
public static void main(String[] args) {
Node full = new Node(1,
new Node(2, new Node(4), new Node(5)),
new Node(3, new Node(6), new Node(7)));
System.out.println(verticalOrder(full)); // [[4], [2], [1, 5, 6], [3], [7]]
Node tree = new Node(3, new Node(9), new Node(20, new Node(15), new Node(7)));
System.out.println(verticalOrder(tree)); // [[9], [3, 15], [20], [7]]
System.out.println(verticalOrder(new Node(8))); // [[8]]
System.out.println(verticalOrder(null)); // []
}
}

Let us read verticalOrder in the order it runs. An empty tree returns an empty list at once, before any work. Then we create the map called columns, set minCol and maxCol to 0, and put the root into the queue as the pair (root, 0).

The while loop runs once per node. poll takes the pair at the front of the queue. The line with computeIfAbsent does two things in one call: if this column has no list yet, it creates an empty ArrayList for it, and either way it returns the list, so add can append the value. Next we update minCol and maxCol. Then we queue the left child with column - 1 and the right child with column + 1, left first, which is what keeps each row in left-to-right order.

When the queue is empty, the for loop walks c from minCol to maxCol and adds each column's list to the result. Because the columns have no gaps, columns.get(c) never returns null here. The walk uses an ArrayDeque instead of recursion, so even a chain of 100,000 nodes cannot overflow the call stack.

In main, the second tree has 9 on the left of 3, and 20 on the right with children 15 and 7. Node 15 is in column 1 - 1 = 0, the same column as the root, so the result is [[9], [3, 15], [20], [7]], root first because it is higher.

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

Let us count on the example first. Each of the 7 nodes entered the queue once and left it once, and each caused one append to a list, so the loop ran 7 times. Reading the result took 5 steps, one per column. For n nodes and w columns that is about n + w steps, and w is never more than n, so the time is O(n). Each map append is O(1) on average, because looking up a column in a HashMap is constant time on average.

For space, the map holds every value exactly once, which is O(n), and the queue holds at most about one row of the tree at a time, which is also at most O(n). So the extra space is O(n).

Comparing the approaches
ApproachTimeExtra spaceOrder inside a column
One level-order walk per columnO(n x w), up to O(n^2)O(n)correct
Recursive walk with a column mapO(n)O(n), deep recursioncan be wrong
One BFS, TreeMap of columnsO(n log w)O(n)correct
One BFS, HashMap with min and maxO(n)O(n)correct

The edge cases need no extra code. An empty tree returns [] from the first check. A single node returns [[8]], one column with one value. A tree that leans entirely to the left gives one node per column, from minus its depth up to 0, and the gap-free range covers them all. A very deep tree is safe because the walk uses a queue instead of recursion.

The mistake beginners most often make is to collect columns with a recursive walk and forget that it can put a lower node before a higher one, exactly like the [8, 3] trap. The second most common is to read the map with a loop from 0 upward and miss every negative column.

8Follow-up questions

What if nodes in the same row and column must be sorted by value?

That stricter version is often called vertical order traversal. BFS alone no longer settles ties, because it orders same-row nodes by position, not value. So during any walk we record each node as three numbers, its column, its row and its value. Then we sort these triples by column, then by row, then by value, and group them by column. The sort makes the cost O(n log n), which is the price of the extra rule.

How would you print the top view or the bottom view of the tree?

With the same BFS and the same columns. For the top view, we keep only the first node we meet in each column, since BFS meets the highest one first; on our tree that gives 4, 2, 1, 3, 7. For the bottom view, we overwrite the column's entry every time, so the last node, the lowest, wins; on our tree, 6 overwrites 5 in column 0, giving 4, 2, 6, 3, 7. Both are O(n), and we still read the columns from min to max.

Why not simply use a TreeMap so the columns come out sorted?

A TreeMap keeps its keys in order, so it would work and is a reasonable answer to give. But each insertion and lookup costs O(log w) instead of O(1) on average, making the walk O(n log w). Because the columns form an unbroken range, tracking the smallest and largest column gives the same order for free, which is why the HashMap version is a little better.

9Conclusion

We printed the tree column by column by giving every node a column number, 0 at the root, one less for a left child and one more for a right child, and by walking the tree once in breadth-first order so that each column fills from top to bottom. Reading the map from the smallest to the largest column gives the answer in O(n) time and O(n) space. The clue to remember is a grouping by position with an order inside each group: carry the position with each node, and pick the walk whose order matches the answer.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me fix the rules first: the root is column 0, a left child is its parent's column minus one and a right child plus one, I return the columns from leftmost to rightmost, each top to bottom, and nodes sharing a row and column come left to right.

Then, if they want more

An empty tree gives an empty list. A first approach walks the whole tree once per column, which is O(n times w) and O(n^2) for a skewed tree. Instead I do one breadth-first search with a queue of node and column pairs.

When I take a pair out, I append the value to a HashMap entry for its column and queue the children with column minus one and plus one. BFS takes whole rows in order and each row left to right, so every column is already top to bottom; a depth-first walk could put a deeper node first.

I also track the smallest and largest column. Columns have no gaps, because each child is one step from its parent, so I read the map from min to max with no sorting. That is O(n) time and O(n) space, and with an explicit queue there is no recursion depth problem.

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 18 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 column by column, in vertical order.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-a-binary-tree-column-by-column-in-vertical-order-1cab20/