Vertical order traversal
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Vertical order traversal slices a tree into columns, as if drawing vertical lines through it, and returns each column from left to right, top to bottom inside a column. It is the foundation of drawing tree layouts and of several view problems.
Practical use cases
- Web app: Family tree drawn in columns. A genealogy site lays out a family tree on screen. Each person needs an x position so that nobody overlaps. Giving each node a column number and grouping nodes by it produces the drawing grid, and the page knows how wide the picture must be.
- Web app: Chart and diagram layout in a dashboard. A flowchart builder in the browser lays out boxes so that parents sit above children. Grouping boxes by column gives the page the left-to-right order for its canvas. A diagram of 80 boxes is laid out in a single pass.
- System: CAD tools and the top and bottom views. Drawing and CAD software group shapes into vertical strips to render them in order. The top view and bottom view problems are just this grouping with only one item kept per column. If you can group by column, many layout questions become easy.
The story: The Class Photo Columns
For the school annual day, Mrs. Sharma's class stood on the stage steps for a photo: one tall child at the top, two below, then more below them. The photographer shouted, "I want a list of names column by column, left to right, and inside each column from top to bottom!"
The children were confused: nobody stood in a neat grid. Aarav had an idea. "Let's give the top child column 0. If you stand down-left of someone, your column is one less than theirs. If you stand down-right, one more." Suddenly everyone knew their column.
Then the photographer walked through the stage row by row from the top, writing each name under its column number. When he finished, column -2 held one child, column -1 held two, and so on. Reading the columns from left to right gave the final list. That slicing of a tree into vertical columns is the vertical order traversal.
How to spot this problem, and where you need it
You must place tree nodes on a screen or grid and need to know which nodes share the same left-to-right position.
Signs you need it
- The task says "vertical order", "group by column", or "horizontal distance from the root".
- Drawn boxes of a tree overlap on screen because you are using only depth to place them.
- Two nodes in the same column but different rows must be kept in top-to-bottom order, and ties need a clear rule.
Where to use it in a project
- Tree and flowchart layout in diagram editors, family tree pages and org chart renderers.
- Any feature that needs the top, bottom or side view of a hierarchy, since they all start from columns.
The solution
Number the columns: root is 0, a left child is one less, a right child is one more. Walk level by level with a queue, carrying each node's column, and put the value into a map from column to a list. At the end sort the column numbers and output the lists in order. Level-order keeps top-to-bottom order inside each column.
Payoff: Before: guessing positions and getting overlaps on 30 nodes. After: every node gets an exact column, and the drawing never overlaps.
Explain it like I am 8
Imagine drawing straight vertical lines through a family tree picture. Everyone the same line cuts goes in one group. Read the groups from left to right, and inside each group from top to bottom.
How it works, step by step
- Give the root column 0. A left child is column - 1, a right child is column + 1.
- Walk the tree level by level so that, inside a column, upper nodes are met before lower ones.
- Keep a table
column → list of valuesand append each node to its column's list. - Sort the column numbers and output the lists from the smallest column to the largest.
The code in four languages
PHP
<?php
class Node {
public ?Node $left = null;
public ?Node $right = null;
public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
if ($n === null) return new Node($v);
if ($v < $n->val) $n->left = insert($n->left, $v);
else $n->right = insert($n->right, $v);
return $n;
}
function verticalOrder(?Node $root): array {
if ($root === null) return [];
$cols = []; // column => list of values, top to bottom
$queue = [[$root, 0]];
while ($queue) {
[$node, $col] = array_shift($queue);
$cols[$col][] = $node->val; // append to this column
if ($node->left) $queue[] = [$node->left, $col - 1];
if ($node->right) $queue[] = [$node->right, $col + 1];
}
ksort($cols); // left-most column first
return array_values($cols);
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
foreach (verticalOrder($root) as $col) echo '[', implode(',', $col), '] ';
echo PHP_EOL; // [1] [3,4] [8,6] [10,7,13] [14]JavaScript
class Node {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
if (n === null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
function verticalOrder(root) {
if (root === null) return [];
const cols = new Map(); // column -> list of values, top to bottom
const queue = [[root, 0]];
while (queue.length) {
const [node, col] = queue.shift();
if (!cols.has(col)) cols.set(col, []);
cols.get(col).push(node.val); // append to this column
if (node.left) queue.push([node.left, col - 1]);
if (node.right) queue.push([node.right, col + 1]);
}
const keys = [...cols.keys()].sort((a, b) => a - b); // left-most column first
return keys.map(k => cols.get(k));
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log(verticalOrder(root).map(c => '[' + c.join(',') + ']').join(' '));
// [1] [3,4] [8,6] [10,7,13] [14]Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
static Node insert(Node n, int v) {
if (n == null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
static Node buildDemo() {
Node root = null;
for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
return root;
}
record Item(Node node, int col) {}
static List<List<Integer>> verticalOrder(Node root) {
if (root == null) return new ArrayList<>();
Map<Integer, List<Integer>> cols = new TreeMap<>(); // column -> values, top to bottom (sorted by column)
Queue<Item> queue = new ArrayDeque<>();
queue.add(new Item(root, 0));
while (!queue.isEmpty()) {
Item item = queue.poll();
cols.computeIfAbsent(item.col(), k -> new ArrayList<>()).add(item.node().val); // append to this column
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<>(cols.values()); // left-most column first
}
public static void main(String[] args) {
String text = verticalOrder(buildDemo()).stream()
.map(c -> c.stream().map(String::valueOf).collect(Collectors.joining(",", "[", "]")))
.collect(Collectors.joining(" "));
System.out.println(text);
// [1] [3,4] [8,6] [10,7,13] [14]
}
}Go
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
type Node struct {
val int
left, right *Node
}
func insert(n *Node, v int) *Node {
if n == nil {
return &Node{val: v}
}
if v < n.val {
n.left = insert(n.left, v)
} else {
n.right = insert(n.right, v)
}
return n
}
func buildDemo() *Node {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
return root
}
type item struct {
node *Node
col int
}
func verticalOrder(root *Node) [][]int {
if root == nil {
return [][]int{}
}
cols := map[int][]int{} // column -> values, top to bottom
queue := []item{{root, 0}}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
cols[cur.col] = append(cols[cur.col], cur.node.val) // append to this column
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})
}
}
keys := []int{}
for k := range cols {
keys = append(keys, k)
}
sort.Ints(keys) // left-most column first
out := [][]int{}
for _, k := range keys {
out = append(out, cols[k])
}
return out
}
func main() {
groups := []string{}
for _, col := range verticalOrder(buildDemo()) {
parts := []string{}
for _, v := range col {
parts = append(parts, strconv.Itoa(v))
}
groups = append(groups, "["+strings.Join(parts, ",")+"]")
}
fmt.Println(strings.Join(groups, " "))
// [1] [3,4] [8,6] [10,7,13] [14]
}Time: O(n log n) · Extra space: O(n). One pass over the nodes, plus sorting the column numbers (never more than n columns).
Watch out for
- Using depth-first order, which can put a lower node before a higher one in the same column. Level order keeps top-to-bottom order.
- Forgetting to sort the columns: hash tables do not remember the left-to-right order.
- Assuming ties are obvious. If two nodes share both row and column, decide a rule (left-to-right, or smaller value first) and stick to it.
Quick check
- What column does the right child of a column -1 node get?
- -2
- 0
- -1
- Why walk level by level?
- It is the only way to visit all nodes
- So inside a column, upper nodes come first
- To avoid sorting
- In our tree, which values share column 1?
- 10, 7, 13
- 14 only
- 3, 4