Magicsheet logo

Binary Tree Vertical Order Traversal

Medium
35.8%
Updated 6/1/2025

Binary Tree Vertical Order Traversal

What is this problem about?

The Binary Tree Vertical Order Traversal interview question asks you to group nodes of a binary tree that share the same horizontal distance from the root. Imagine a vertical line passing through each node; you need to return the nodes level-by-level (top to bottom) for each of these vertical lines, ordered from the leftmost column to the rightmost column.

Why is this asked in interviews?

Companies like Meta, Amazon, and Google use this problem to test your ability to coordinate multiple coordinate systems. You're not just dealing with the tree's depth (levels), but also its horizontal positioning. It requires a solid grasp of Breadth-First Search (BFS) combined with Hash Table data structures. It evaluates how you handle grouping and sorting of results in a multi-dimensional way.

Algorithmic pattern used

This problem is best solved using a Breadth-First Search (BFS) along with a Hash Table (Map). You assign the root a horizontal coordinate of 0. Its left child gets -1, and its right child gets +1. As you traverse using BFS (which ensures top-to-bottom order), you store the nodes in a map where the key is the horizontal coordinate and the value is a list of nodes at that coordinate. Finally, you sort the keys and return the lists.

Example explanation

Consider this tree: 3 / 9 20 /
15 7

  1. Root (3) is at col 0. Map: {0: [3]}
  2. Left (9) is at col -1. Map: {-1: [9], 0: [3]}
  3. Right (20) is at col +1. Map: {-1: [9], 0: [3], 1: [20]}
  4. Child (15) is at col 1-1 = 0. Map: {-1: [9], 0: [3, 15], 1: [20]}
  5. Child (7) is at col 1+1 = 2. Map: {-1: [9], 0: [3, 15], 1: [20], 2: [7]} Final Output (Sorted by keys): [[9], [3, 15], [20], [7]]

Common mistakes candidates make

A common mistake is using DFS instead of BFS. In vertical order traversal, if two nodes are in the same column, the one on the higher level (closer to the root) must come first. DFS doesn't naturally guarantee this, whereas BFS does. Another mistake is forgetting to keep track of the minimum and maximum horizontal coordinates to avoid a separate sorting step at the end.

Interview preparation tip

When you hear "vertical order" or "column-wise," think "horizontal distance." Start by assigning the root a coordinate of 0 and see how its children's coordinates relate to it. Mastering the combination of a Queue and a Map is key to this problem.

Similar Questions