Top view
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The top view is what you see looking straight down at a tree: nodes that share the same vertical line overlap, and only the highest one in each line shows. It introduces the idea of giving every node a column position.
Practical use cases
- Web app: Seating plan seen from above. A wedding or event-booking page draws tables as a tree with hosts at the top and guests below. The floor plan view needs one visible head per column so labels do not overlap. Assigning each table a column number and keeping the highest in each column draws a clean plan.
- Web app: Dashboard hierarchy minimap. An admin dashboard shows a small minimap of a team hierarchy. Many people sit beneath each other in the same visual column, so the minimap shows only the highest person per column. It stays readable for teams of hundreds. Nobody has to zoom in just to read a name.
- System: Maps and top-down games. A top-down game looks at a world from above, so when objects stack in the same spot only the topmost is drawn. Map renderers make the same choice when several features share a location. The result is a clean picture instead of a pile of overlapping labels.
The story: The Drone Over the Wedding Pandal
Zoya's cousin's wedding had a huge pandal, decorated with hanging marigold strings in tree-shaped layers. The photographer, Aarav, flew a small drone high above it to take one picture straight down. "What will be in the photo?" Mira asked.
Kabir worked it out. "The pandal is laid out in vertical lanes, like columns on a street. In each lane there may be several strings, one below the other. From the top, only the highest one in each lane is visible. The ones under it are hidden."
So Mira numbered the lanes. The middle lane (under the main entrance) was 0, the lane to the left was -1, the next -2; the lanes to the right were 1, 2. Going to a left child moved one lane left, going to a right child moved one lane right. Then they walked the pandal from the top downwards, row by row, and in every lane wrote down only the first string they met.
Reading the lanes from far left to far right gave the photo: the top view. Notice the twist: two strings in different branches could land in the same lane, and the higher one hides the lower one!
How to spot this problem, and where you need it
Items in a layered structure line up in vertical columns, and you only want the highest visible item in each column, as if viewed from directly above.
Signs you need it
- The task mentions "seen from above", "top-most node per vertical line" or "horizontal distance from the root".
- You are drawing a tree on a canvas and labels for different nodes land on the same x position and overlap.
- You need a column number for each node, with the root at 0, left children at minus one and right children at plus one.
Where to use it in a project
- Drawing diagrams and minimaps where overlapping elements should be hidden under the highest one.
- Top-down rendering in simple games and map layers where the highest object hides the ones under it.
The solution
Give the root column 0, a left child one column less, and a right child one more. Walk level by level with a queue, carrying the column along. The first time you see a column, record that node as its top view and ignore later ones. Finally, read the columns from smallest to largest.
Payoff: Before: overlapping labels from 40 nodes drawn on 9 columns. After: 9 clean labels, one per column, found in one pass.
Explain it like I am 8
Stand above a tree and look straight down. Nodes hang in invisible vertical lines. In each line you only see the top-most node, because the ones below it are hidden underneath. The top view is what you see, from the left line to the right line.
How it works, step by step
- Give the root the column number 0. A left child gets
column - 1, a right child getscolumn + 1. - Walk the tree level by level (BFS with a queue), carrying each node's column number along.
- Keep a map from column to value. The first node to reach a column is the one closest to the top, so store it and ignore later ones.
- Because BFS visits upper levels first, the first node in each column is always the highest.
- At the end, sort the columns from smallest to largest and read off the values: that is the top view.
The code in four languages
PHP
<?php
class TreeNode {
public ?TreeNode $left = null;
public ?TreeNode $right = null;
public function __construct(public int $val) {}
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree(): TreeNode {
$root = new TreeNode(1);
$root->left = new TreeNode(2);
$root->right = new TreeNode(3);
$root->left->left = new TreeNode(4);
$root->left->right = new TreeNode(5);
$root->right->right = new TreeNode(6);
$root->left->right->left = new TreeNode(7);
return $root;
}
// Top view: BFS so higher nodes come first; remember the first node seen in every column.
function topView(?TreeNode $root): array {
if ($root === null) return [];
$seen = []; // column => value
$queue = [[$root, 0]]; // each entry: [node, column]
while ($queue) {
[$node, $col] = array_shift($queue);
if (!isset($seen[$col])) $seen[$col] = $node->val; // first one in this column wins
if ($node->left) $queue[] = [$node->left, $col - 1];
if ($node->right) $queue[] = [$node->right, $col + 1];
}
ksort($seen); // left-most column first
return array_values($seen);
}
echo implode(' ', topView(sampleTree())) . PHP_EOL; // 4 2 1 3 6JavaScript
class TreeNode {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree() {
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
// Top view: BFS so higher nodes come first; remember the first node seen in every column.
function topView(root) {
if (root === null) return [];
const seen = new Map(); // column -> value
const queue = [[root, 0]]; // each entry: [node, column]
while (queue.length) {
const [node, col] = queue.shift();
if (!seen.has(col)) seen.set(col, node.val); // first one in this column wins
if (node.left) queue.push([node.left, col - 1]);
if (node.right) queue.push([node.right, col + 1]);
}
const cols = Array.from(seen.keys()).sort((a, b) => a - b); // left-most column first
return cols.map(c => seen.get(c));
}
console.log(topView(sampleTree()).join(' ')); // 4 2 1 3 6Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
static TreeNode sampleTree() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
static String join(List<Integer> xs) {
return xs.stream().map(String::valueOf).collect(Collectors.joining(" "));
}
// Each queue entry remembers which column its node sits in.
record Item(TreeNode node, int col) {}
// Top view: BFS so higher nodes come first; remember the first node seen in every column.
static List<Integer> topView(TreeNode root) {
if (root == null) return new ArrayList<>();
Map<Integer, Integer> seen = new TreeMap<>(); // column -> value (TreeMap keeps columns sorted)
Queue<Item> queue = new ArrayDeque<>();
queue.add(new Item(root, 0));
while (!queue.isEmpty()) {
Item item = queue.poll();
seen.putIfAbsent(item.col(), item.node().val); // first one in this column wins
if (item.node().left != null) queue.add(new Item(item.node().left, item.col() - 1));
if (item.node().right != null) queue.add(new Item(item.node().right, item.col() + 1));
}
return new ArrayList<>(seen.values()); // left-most column first
}
public static void main(String[] args) {
System.out.println(join(topView(sampleTree()))); // 4 2 1 3 6
}
}Go
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// The example tree: 1
//
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
func sampleTree() *TreeNode {
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Right.Left = &TreeNode{Val: 7}
return root
}
// item remembers which column a node sits in.
type item struct {
node *TreeNode
col int
}
// topView does BFS so higher nodes come first; it remembers the first node seen in every column.
func topView(root *TreeNode) []int {
if root == nil {
return []int{}
}
seen := map[int]int{} // column -> value
queue := []item{{root, 0}}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
if _, ok := seen[cur.col]; !ok {
seen[cur.col] = cur.node.Val // first one in this column wins
}
if cur.node.Left != nil {
queue = append(queue, item{cur.node.Left, cur.col - 1})
}
if cur.node.Right != nil {
queue = append(queue, item{cur.node.Right, cur.col + 1})
}
}
cols := []int{}
for c := range seen {
cols = append(cols, c)
}
sort.Ints(cols) // left-most column first
out := []int{}
for _, c := range cols {
out = append(out, seen[c])
}
return out
}
// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
parts := make([]string, len(xs))
for i, v := range xs {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(joinInts(topView(sampleTree()), " ")) // 4 2 1 3 6
}Time: O(n log n) · Extra space: O(n). The walk is O(n); sorting the columns at the end adds a log factor (it is O(n) if you track the min and max column instead).
Watch out for
- Using DFS (preorder) and keeping the first node seen per column. A deeper node can be reached first and wrongly win; go level by level so higher nodes come first.
- Forgetting to sort the columns before printing, so the view comes out in the order columns were discovered.
- Thinking each level adds a new column. Different nodes on different levels can share a column, and the deeper one is hidden.
Quick check
- What is the top view of our example tree?
- 1 2 3 4 5 6 7
- 4 2 1 3 6
- 4 2 7 5 1 3 6
- Which column does node 5 (the right child of 2) belong to?
- -2
- -1
- 0
- 1
- Why do we use BFS (level order) for the top view?
- It sorts the columns for us
- It is faster than DFS in every case
- Higher nodes are reached first, so the first node in a column is the top one