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

Print the top view of a binary tree.

1What the top view of a tree means

Imagine a set of lamps hanging from a ceiling on strings of different lengths, each lamp a little to the left or right of the one above it. Now lie on the floor and look straight up, or better, imagine standing on the ceiling and looking straight down. Lamps that hang in the same vertical line hide each other, and in each line you see only the highest lamp. Read those lamps from left to right, and you have the top view.

A binary tree is exactly such a set of lamps. Each node is a lamp, the root hangs highest, and every node can have a left child hanging below it and to the left, and a right child below and to the right. To make vertical lines exact, we give every node a number called its column, or horizontal distance. The root is in column 0. A left child is in its parent's column minus 1, and a right child is in its parent's column plus 1. The top view lists, for each column from the leftmost to the rightmost, the highest node in that column.

Trees can feel intimidating, so let me reassure you that nothing here needs a new idea. We will only number the nodes by column and visit them in a sensible order, and both of those are things you can do with a pencil.

Let us keep one example for the whole article. The root is 1, with left child 2 and right child 3. Node 2 has a right child 4, node 4 has a right child 5, and node 3 has a right child 6. Work out the columns with me: 1 is in column 0, 2 in -1, 3 in 1. Node 4 is the right child of 2, so it is in -1 + 1 = 0. Node 5 is the right child of 4, so 0 + 1 = 1. Node 6 is the right child of 3, so 1 + 1 = 2.

PictureThe example tree and what is seen from above

Found nodes are seen from above; dim nodes are hidden under a higher node in the same column.

  1. 123465
    column -1
    2
    column 0
    1, hides 4
    column 1
    3, hides 5
    column 2
    6
    top view
    [2, 1, 3, 6]

    1Columns run from -1 to 2. Node 4 sits in column 0 under the root, and node 5 in column 1 under node 3, so both are hidden. The top view is [2, 1, 3, 6].

What to assume

If two nodes share a column and a level, which one is seen?
We take the one further left in that level.
Do we print or return the values?
We return a list, from the leftmost column to the rightmost.
What about an empty tree?
We return an empty list.
Can the tree be very deep?
Possibly, so a long chain of nodes must not overflow the call stack.

Now look down each column. Column -1 holds only 2. Column 0 holds 1 and 4, and 1 is higher, so 4 is hidden. Column 1 holds 3 and 5, and 3 is higher, so 5 is hidden. Column 2 holds only 6. The top view is [2, 1, 3, 6]. Notice that 5 is hidden even though it sits far from 3 in the tree; it just happens to hang in the same vertical line.

A careful candidate asks a few questions first. If two nodes share a column and a level, which one is seen? We take the one further left in that level. Do we print or return the values? We return a list, from the leftmost column to the rightmost. What about an empty tree? We return an empty list. Can the tree be very deep? Possibly, so we will avoid recursion in the final answer, so that a long chain of nodes cannot overflow the call stack.

2How to recognise this kind of tree problem

A beginner reading the question for the first time usually thinks of walking the tree, which is right, and then of noting down the first node seen in each column. The doubt is which walk to use. Most of us learn the recursive walks first, pre-order, in-order and post-order, which go deep down one branch before coming back, so it feels natural to reach for one of them.

So let us take the clues one at a time. The first clue is the word top. Being on top means being closest to the root, so the answer depends on each node's depth, its level counted from the root at level 0. Whenever the answer depends on which node is highest, the order in which we visit nodes matters, and the order that visits higher nodes first is visiting level by level.

The second clue is the word view, from above. A view from above cares about left and right positions, so every node needs a horizontal coordinate. That is the column we just worked out, and it can be carried down the tree, since each child's column comes from its parent's.

The third clue is the phrase print the top view, which means each column contributes one node and the columns come out in order from left to right. So we will need a map from column to node, and a map that keeps its keys sorted gives the left-to-right order for free.

Together these clues point to the trees pattern, and in particular to breadth-first search with a coordinate on each node. Breadth-first search, BFS for short, visits the root, then every node on level 1, then every node on level 2, and so on, using a queue, a waiting line where items join at the back and leave from the front. The rule to carry to new problems is that when the answer depends on the first, highest or closest node per level or per column, visit level by level and give each node the coordinate the question cares about. The left view, the right view, the bottom view and vertical order traversal are all solved this way.

The look-alike is a depth-first walk, which also visits every node but goes deep before wide. In pre-order, a deep node in the left subtree can be met before a shallow node in the right subtree, so first met does not mean highest. We will see that go wrong on our example in a moment.

3The honest first attempt, looking down each column in turn

The honest first attempt follows the definition word for word: for each column, look down it and find the highest node. To do that, we first walk the tree once to learn the leftmost and rightmost columns. Then, for each column c in that range, we walk the whole tree again, carrying each node's column and depth, and keep the node in column c with the smallest depth. This is clearly correct, which makes it a good start.

Let us run it by hand. The first walk finds columns from -1 to 2. The walk for column -1 visits all six nodes and keeps 2. The walk for column 0 visits all six and keeps 1, because 1 is at depth 0 and 4 at depth 2. The walk for column 1 keeps 3 over 5, and the walk for column 2 keeps 6. The answer is [2, 1, 3, 6].

Java
static List<Integer> topViewBrute(Node root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
int[] range = {0, 0}; // leftmost and rightmost column
findRange(root, 0, range);
for (int c = range[0]; c <= range[1]; c++) { // one whole walk for every column
int[] best = {Integer.MAX_VALUE, 0}; // {depth, value} of the highest node so far
search(root, 0, 0, c, best);
out.add(best[1]);
}
return out;
}
static void findRange(Node n, int col, int[] range) {
if (n == null) return;
range[0] = Math.min(range[0], col);
range[1] = Math.max(range[1], col);
findRange(n.left, col - 1, range);
findRange(n.right, col + 1, range);
}
static void search(Node n, int col, int depth, int c, int[] best) {
if (n == null) return;
if (col == c && depth < best[0]) { best[0] = depth; best[1] = n.val; } // higher than any so far
search(n.left, col - 1, depth + 1, c, best);
search(n.right, col + 1, depth + 1, c, best);
}

Now let us count. Our tree has six nodes and four columns, so the method made 6 visits to find the range and 4 times 6 more, 30 visits in all, to look at a six-node tree. In general, with n nodes and w columns, it makes about n times w visits. A tree that is a long chain going down to the right has a new column for every node, so w is close to n and the time is O(n squared). The space is the recursion depth, up to O(n) for a chain.

Where is the waste? Every column's walk visits every node, and almost all of those visits are about other columns. When we walked the tree for column -1, we passed node 1 and node 3 and learned nothing about columns 0 and 1, then walked past them again for the next column.

4Getting to breadth-first search, one observation at a time

The natural shortcut is to fill every column in a single walk, visiting each node once and recording it for its column if that column is still empty. That would be n visits instead of n times w. Will it work? It depends on the order of the walk, so let us try it with the walk most of us learn first, pre-order, which visits a node, then its whole left subtree, then its whole right subtree.

Step throughWhy recording the first node in pre-order goes wrong

The walk goes root, then left subtree, then right subtree. Recorded nodes are marked found, skipped ones dim.

  1. 123465
    visit
    1 in column 0
    recorded?
    yes
    columns
    {0=1}

    1Pre-order starts at the root. Node 1 is in column 0, which is empty, so we record 1 for column 0.

  2. 123465
    visit
    2 in column -1
    recorded?
    yes
    columns
    {-1=2, 0=1}

    2Next comes the left child, 2, in column -1. That column is empty, so we record 2.

  3. 123465
    visit
    4 in column 0
    recorded?
    no, column taken
    columns
    {-1=2, 0=1}

    3Pre-order keeps going down the left side to 4, in column 0. Column 0 already holds 1, so 4 is skipped, which is right, because 1 is above it.

  4. 123465
    visit
    5 in column 1
    recorded?
    yes
    columns
    {-1=2, 0=1, 1=5}

    4Still going down, we reach 5 in column 1 at depth 3. Column 1 is empty, because 3 has not been visited yet, so 5 is recorded. This is the mistake.

  5. 123465
    visit
    3 in column 1
    recorded?
    no, column taken
    columns
    {-1=2, 0=1, 1=5}

    5Only now does pre-order reach 3, in column 1 at depth 1, much higher than 5. But column 1 is taken, so the node that is really on top is thrown away.

  6. 123465
    visit
    6 in column 2
    recorded?
    yes
    columns
    {-1=2, 0=1, 1=5, 2=6}
    true top view
    [2, 1, 3, 6]

    6Last comes 6, in column 2. The walk returns [2, 1, 5, 6], while the true top view is [2, 1, 3, 6].

The pre-order walk failed in one precise place. When it reached 5, column 1 was still empty, because 3, the higher node in that column, lives in the right subtree, which pre-order visits last. So the first node met in a column was not the highest one. The single walk is a good idea; only its order was wrong.

So let us ask the question that fixes it. In what order must we visit nodes so that the first node we meet in any column is always the highest one in that column? The answer is to visit in order of depth, all of level 0, then all of level 1, then all of level 2. If we never visit a node until every higher node has been visited, then whichever node first claims a column has no higher rival left to come.

Visiting level by level is breadth-first search. We keep a queue. We start by putting the root in it. Then, again and again, we take the node at the front, deal with it, and put its children at the back. Because a node's children join behind every node already waiting, all of one level leave the queue before any of the next. On our tree the queue releases 1, then 2 and 3, then 4 and 6, then 5.

A beginner then asks how a node in the queue knows its column, since the queue only holds nodes. The answer is to put the column into the queue with the node, as a pair. When we take a node out, we know its column, and its children's columns are that number minus 1 and plus 1. In Java a small record, Item(node, column), holds the pair.

Dealing with a node takes one line, firstInColumn.putIfAbsent(column, value). putIfAbsent stores the value only if that column has no value yet, and otherwise does nothing. So the first node BFS meets in a column wins, and because BFS meets higher levels first, that is the highest node. Within one level BFS goes from left to right, which settles ties on the same level in favour of the leftmost, the rule we agreed with the interviewer.

Finally, the map is a TreeMap, a map that keeps its keys in sorted order. Our keys are columns, so reading its values gives them from the leftmost column to the rightmost, and no separate sort is needed.

5Watching breadth-first search on the example

The picture below plays the method on our tree, one node taken from the queue per frame. The label poll marks the node just taken. Nodes still waiting in the queue are marked as compared, stored nodes as found, and nodes that turned out to be hidden are dimmed. The panel shows the map from column to value and the queue, written as value@column.

Watch the order in which nodes leave the queue, and compare it with the pre-order picture. This time 3 leaves before 4 and 5, because it is on a higher level.

Step throughBreadth-first search with columns on the example tree

poll marks the node just taken from the queue. Compared nodes are waiting in the queue; found nodes were stored; dim nodes were hidden.

  1. 123465
    queue
    1@0
    map
    {}

    1We put the root in the queue with column 0. Nothing has been stored yet. The queue is written as value@column.

  2. 1poll23465
    took
    1 in column 0
    stored?
    yes
    map
    {0=1}
    queue
    2@-1 3@1

    2We take 1 from the front of the queue. Column 0 is empty, so putIfAbsent stores 1 there. Its children go to the back: 2 in column -1 and 3 in column 1.

  3. 12poll3465
    took
    2 in column -1
    stored?
    yes
    map
    {-1=2, 0=1}
    queue
    3@1 4@0

    3We take 2, in column -1. That column is empty, so 2 is stored. Its only child, 4, joins the back of the queue in column -1 + 1 = 0.

  4. 123poll465
    took
    3 in column 1
    stored?
    yes
    map
    {-1=2, 0=1, 1=3}
    queue
    4@0 6@2

    4We take 3, in column 1. Column 1 is empty, so 3 is stored. Notice that it arrives before 5, because 3 is on a higher level. Its child 6 joins in column 2.

  5. 1234poll65
    took
    4 in column 0
    stored?
    no, hidden
    map
    {-1=2, 0=1, 1=3}
    queue
    6@2 5@1

    5We take 4, in column 0. Column 0 already holds 1, which BFS met on an earlier level, so putIfAbsent leaves it alone. 4 is hidden. Its child 5 joins in column 1.

  6. 12346poll5
    took
    6 in column 2
    stored?
    yes
    map
    {-1=2, 0=1, 1=3, 2=6}
    queue
    5@1

    6We take 6, in column 2. That column is empty, so 6 is stored. 6 has no children, so the queue now holds only 5.

  7. 123465poll
    took
    5 in column 1
    stored?
    no, hidden
    map
    {-1=2, 0=1, 1=3, 2=6}
    queue
    empty

    7We take 5, in column 1. Column 1 already holds 3, from level 1, so 5 is hidden. This is the node the pre-order walk wrongly recorded.

  8. 123465
    map
    {-1=2, 0=1, 1=3, 2=6}
    answer
    [2, 1, 3, 6]

    8The queue is empty, so the loop ends. The TreeMap lists its columns from -1 to 2, so the method returns [2, 1, 3, 6].

Let us read the important frames back. In the fourth frame, 3 is taken while 5 has not even entered the queue, so 3 claims column 1. This is exactly what the pre-order walk could not do.

In the fifth frame, 4 is taken in column 0. The map already holds 1 there, stored from level 0, so putIfAbsent changes nothing, and 4 is correctly hidden. In the seventh frame, 5 is taken in column 1 and meets 3 already there, so 5 is hidden too.

In the last frame the queue is empty. The TreeMap holds -1 = 2, 0 = 1, 1 = 3 and 2 = 6, sorted by column, so its values give [2, 1, 3, 6].

6The complete Java program

Here is the full program, with a small Node class, the Item record that pairs a node with its column, and topView. main prints the top view of our example, of a full tree with seven nodes, of a single node and of an empty tree, and each comment shows what that line prints.

Java
import java.util.*;
public class TopView {
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); }
}
record Item(Node node, int column) {}
// Nodes seen from above, left to right: the first node BFS meets in each column.
static List<Integer> topView(Node root) {
Map<Integer, Integer> firstInColumn = new TreeMap<>(); // column -> value, sorted
Deque<Item> queue = new ArrayDeque<>();
if (root != null) queue.add(new Item(root, 0));
while (!queue.isEmpty()) {
Item it = queue.poll();
firstInColumn.putIfAbsent(it.column(), it.node().val); // higher levels come first
if (it.node().left != null) queue.add(new Item(it.node().left, it.column() - 1));
if (it.node().right != null) queue.add(new Item(it.node().right, it.column() + 1));
}
return new ArrayList<>(firstInColumn.values());
}
public static void main(String[] args) {
// 1
// / \
// 2 3
// \ \
// 4 6
// \
// 5
Node tree = new Node(1, new Node(2, null, new Node(4, null, new Node(5))), new Node(3, null, new Node(6)));
System.out.println(topView(tree)); // [2, 1, 3, 6]
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(topView(full)); // [4, 2, 1, 3, 7]
System.out.println(topView(new Node(9))); // [9]
System.out.println(topView(null)); // []
}
}

Let us read topView in the order it runs. We create firstInColumn, a TreeMap from column to value, and queue, an ArrayDeque used as the waiting line. If the root exists, we put it in the queue with column 0. For an empty tree the queue stays empty, the loop never runs, and we return an empty list.

The while loop runs as long as some node is waiting. queue.poll() takes the item at the front. The next line, putIfAbsent, is the whole decision: it stores the value only if this column has none yet. Then we add the left child, if there is one, with column minus 1, and the right child with column plus 1, both at the back of the queue. The left child is added first, so that within a level nodes leave from left to right.

When the queue is empty, new ArrayList<>(firstInColumn.values()) copies the values in sorted column order. So main prints [2, 1, 3, 6] for our tree, [4, 2, 1, 3, 7] for the full tree, where the root hides 5 and 6 in column 0, [9] for a single node and [] for an empty tree.

The same method gives the bottom view with one change. Use put instead of putIfAbsent, so that the last node BFS meets in each column, the lowest, overwrites the earlier ones.

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

Let us count on the example first. Each of the six nodes entered the queue once and left it once, and each made one call to putIfAbsent, so six map operations against the 30 visits of the first attempt. In general BFS visits each of the n nodes once. Each TreeMap operation costs O(log w), where w is the number of columns, at most n, so the total time is O(n log n) in the worst case.

For space, the queue can hold a whole level at once, and the map holds one entry per column, so both are O(n) in the worst case. If O(n log n) matters, a HashMap with the smallest and largest column remembered gives O(n), because columns are consecutive whole numbers and can be read from min to max at the end.

Comparing the ways to find the top view
ApproachTimeExtra spaceCorrect?
One full walk per columnO(n * w), up to O(n^2)O(n) recursionyes
One pre-order walk, first node per columnO(n log n)O(n)no
BFS with columns and a TreeMapO(n log n)O(n)yes
BFS with columns, HashMap and min, maxO(n)O(n)yes

Now the edges, one at a time. An empty tree never enters the loop and returns []. A single node stores itself in column 0 and returns just its value. A long chain going down to the left gives every node a new column, so every node is seen, and since we use a queue rather than recursion, even a very deep chain cannot overflow the call stack.

Two nodes on the same level in the same column, such as a left child's right child and a right child's left child, are settled by BFS order: the one further left leaves the queue first and claims the column. If the interviewer wants a different rule for such ties, we would store the depth or the value with each entry and compare.

8Follow-up questions

How would you print the left view or the right view instead?

Those are views from the side, so what matters is the level, not the column. With BFS we process the queue one level at a time, by noting the queue's size at the start of each level. The first node taken in each level is in the left view, and the last is in the right view. A depth-first walk that visits left before right and records the first node it meets at each depth also gives the left view, because within a depth it meets the leftmost node first.

How do you print the vertical order traversal?

We keep every node of a column instead of only the first, in a TreeMap from column to a list. Filling the lists in BFS order makes each column list its nodes from top to bottom. Some versions also ask for nodes that share a column and a level to be sorted by value, and then we store the level with each node so we can sort those groups.

Why not fix the pre-order walk instead of switching to BFS?

We can. We store the depth with each column's entry, and when a node arrives at a column whose stored depth is greater, we replace it. That gives the right answer, but every comparison now needs the depth, ties need care, and the recursion can overflow on a deep tree. BFS removes the problem at its root, because its order guarantees that the first node met is the highest.

9Conclusion

We found the top view by giving each node a column, the root at 0, left children one less and right children one more, and by visiting the tree level by level with a queue. Because breadth-first search meets higher nodes before lower ones, the first node it meets in each column is the one seen from above, so putIfAbsent keeps it and a TreeMap returns the columns from left to right. That is O(n log n) time, or O(n) with a HashMap, and O(n) space. The clue to remember is an answer that depends on the highest or first node per column or per level: visit level by level and carry the coordinate.

What to say in the interviewAbout 90 seconds aloud

Open with

I will return the values seen from above, from the leftmost column to the rightmost, an empty list for an empty tree, and on ties in the same level and column I take the leftmost.

Then, if they want more

I give every node a column: the root is 0, a left child is its parent minus 1 and a right child its parent plus 1. A brute force walks the whole tree once per column and keeps the shallowest node, which can be O(n squared).

A single pre-order walk that keeps the first node per column is fast but wrong, because a deep node in the left subtree can reach a column before a shallow node in the right subtree. So I use breadth-first search, which visits every level before the next.

I put pairs of node and column in a queue, starting with the root at column 0. Each time I take a node out, I call putIfAbsent on a TreeMap from column to value, so the first node seen in each column wins, and since BFS meets higher levels first, that node is the top one.

Then I enqueue the left child with column minus 1 and the right child with column plus 1. At the end the TreeMap's values are in column order. That is O(n log n) time, or O(n) with a HashMap and the column range, and O(n) space, with no recursion.

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 the top view of a binary tree.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-the-top-view-of-a-binary-tree-a65b66/