Vertical Order Traversal of a Binary Tree (LeetCode 987): Solution and Explanation
Give every node a coordinate: the root is (row 0, col 0), a left child moves one column left and one row down, a right child one column right. Return the columns from left to right, each read top to bottom, with ties at the same spot ordered by value.
Intuition
Each node's column is just the number of right moves minus the number of left moves on its path from the root, and its row is its depth. A single traversal that carries (row, col) along can label every node.
The output order has three levels: column first, then row within a column, then value when two nodes land on the same row and column. That is exactly the order you get by sorting the tuples (col, row, val).
After the sort, the triples for column -2 come first, then column -1, and so on, so the answer is the sorted list cut wherever the column number changes.
Approach: Label, sort, group
- BFS from the root, carrying (node, row, col) in the queue.
- For every node popped, record the triple (col, row, val), then enqueue its left child at (row + 1, col - 1) and its right child at (row + 1, col + 1).
- Sort all triples. Python and C++ compare tuples lexicographically; elsewhere use a comparator on col, then row, then val.
- Scan the sorted triples, starting a new list whenever the column changes, and append each value to the current list.
Step-by-step example
root = [1,2,3,4,6,5,7]
- BFS records (0,0,1), (-1,1,2), (1,1,3), (-2,2,4), (0,2,6), (0,2,5), (2,2,7).
- Sorting gives (-2,2,4), (-1,1,2), (0,0,1), (0,2,5), (0,2,6), (1,1,3), (2,2,7). Note that 5 and 6 share row 2 and column 0, so 5 comes first by value.
- Grouping by column gives [[4],[2],[1,5,6],[3],[7]].
Code: Python, Java, C++
1class Solution:
2 def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
3 entries = []
4 queue = deque([(root, 0, 0)])
5 while queue:
6 node, row, col = queue.popleft()
7 entries.append((col, row, node.val))
8 if node.left:
9 queue.append((node.left, row + 1, col - 1))
10 if node.right:
11 queue.append((node.right, row + 1, col + 1))
12 entries.sort()
13 result = []
14 last_col = None
15 for col, row, val in entries:
16 if col != last_col:
17 result.append([])
18 last_col = col
19 result[-1].append(val)
20 return result1class Solution {
2 public List<List<Integer>> verticalTraversal(TreeNode root) {
3 List<int[]> entries = new ArrayList<>();
4 Deque<TreeNode> queue = new ArrayDeque<>();
5 Deque<int[]> pos = new ArrayDeque<>();
6 queue.offer(root);
7 pos.offer(new int[]{0, 0});
8 while (!queue.isEmpty()) {
9 TreeNode node = queue.poll();
10 int[] p = pos.poll();
11 entries.add(new int[]{p[1], p[0], node.val});
12 if (node.left != null) {
13 queue.offer(node.left);
14 pos.offer(new int[]{p[0] + 1, p[1] - 1});
15 }
16 if (node.right != null) {
17 queue.offer(node.right);
18 pos.offer(new int[]{p[0] + 1, p[1] + 1});
19 }
20 }
21 entries.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] != b[1] ? a[1] - b[1] : a[2] - b[2]);
22 List<List<Integer>> result = new ArrayList<>();
23 Integer lastCol = null;
24 for (int[] e : entries) {
25 if (lastCol == null || e[0] != lastCol) {
26 result.add(new ArrayList<>());
27 lastCol = e[0];
28 }
29 result.get(result.size() - 1).add(e[2]);
30 }
31 return result;
32 }
33}1class Solution {
2public:
3 vector<vector<int>> verticalTraversal(TreeNode* root) {
4 vector<vector<int>> entries;
5 queue<pair<TreeNode*, pair<int, int>>> q;
6 q.push({root, {0, 0}});
7 while (!q.empty()) {
8 auto cur = q.front();
9 q.pop();
10 TreeNode* node = cur.first;
11 int row = cur.second.first, col = cur.second.second;
12 entries.push_back({col, row, node->val});
13 if (node->left) {
14 q.push({node->left, {row + 1, col - 1}});
15 }
16 if (node->right) {
17 q.push({node->right, {row + 1, col + 1}});
18 }
19 }
20 sort(entries.begin(), entries.end());
21 vector<vector<int>> result;
22 for (size_t i = 0; i < entries.size(); i++) {
23 if (i == 0 || entries[i][0] != entries[i - 1][0]) {
24 result.push_back({});
25 }
26 result.back().push_back(entries[i][2]);
27 }
28 return result;
29 }
30};Time and space complexity
O(n log n)
The traversal is O(n), and sorting n triples is O(n log n).
O(n)
The list of triples and the BFS queue each hold up to n items.
Other approaches
Column map with per-column sort (time O(n log n), space O(n))
Store (row, val) pairs in a hash map keyed by column, track the min and max column, then sort each column's pairs. Same idea, and slightly faster when columns are small, because each sort is over fewer items.
DFS instead of BFS (time O(n log n), space O(n))
A recursive DFS that passes (row, col) works just as well because the sort fixes the order afterward. Only the traversal changes.
Common mistakes
- Relying on BFS order alone for ties. BFS gives top-to-bottom order, but two nodes on the same row and column still need to be ordered by value; that is the difference from the premium problem 314.
- Sorting by (row, col) instead of (col, row). The output is grouped by column first.
- Forgetting that columns can be negative, which breaks a plain array indexed by column unless you offset it.
- Starting a new group on a row change rather than a column change.
Frequently asked questions
Why is this rated Hard when the code is short?
The difficulty is in reading the ordering rules correctly. Once you see that the answer is lexicographic order on (col, row, val), the code is a traversal plus a sort.
How is this different from Binary Tree Vertical Order Traversal (314)?
Problem 314 orders tied nodes left to right as BFS meets them. This problem orders them by value, so it needs an explicit sort on the value as the last key.
Can I avoid the full sort?
Partly. With a map from column to (row, val) pairs and a tracked min and max column, you only sort inside each column. The worst case is still O(n log n) when one column holds most nodes.
Does the traversal order matter?
No. BFS, preorder, or any other order works, because the final sort decides the output order completely.