Vertical Order Traversal of a Binary Tree
Hard
Topics
Give the root column 0; a left child sits one column left of its parent and a right child one column right. Group the nodes by column, ordered from the leftmost column to the rightmost.
Within a column, nodes come top row first. Where two nodes share both a column and a row, they come out in increasing order of value — this is the one difference from the simpler vertical-order problem, which takes them left to right instead.
On this judge the columns are shown separated by |.
Example 1
0, a left child one column to the left of its parent and a right child one to the right. The small number above each node is that column, and the lower rows are the answer, one row per column from leftmost to rightmost. Inside a column the higher node comes first; no two nodes share a row and column here, so the value tie-break never applies.Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: No two nodes share a row and a column here, so the ordering rule never comes up.
Example 2
Input: root = [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: Nodes 5 and 6 share column 0 and row 2. They are reported 5 then 6 by value — and 6 sits to the left of 5 in the drawing, so left-to-right would give the other order.
Example 3
Input: root = [1] Output: [[1]] Explanation: One node in column 0.
Constraints
- 1 <= number of nodes <= 1000
- 0 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
The column of a node follows from the path to it — start at 0, subtract one per left step, add one per right — so it can be carried down during a traversal and needs no reconstruction.
The twist is the tie-break, and it is worth seeing why it is awkward. A breadth-first walk delivers nodes in row order and, within a row, left to right — which is exactly the ordering the other vertical-order problem wants. Here a row-and-column collision is broken by value instead, and traversal order cannot supply that: in example 2 the node with the smaller value sits to the right.
So the traversal can establish the column and the row, and the ordering has to be imposed afterwards. Collect (column, row, value) for every node and sort by all three; the groups then fall out by column.
That is why this problem is graded harder than its sibling despite looking almost identical: the answer is a sort, not a walk.
Approach
- Walk the tree in any order, carrying each node’s column and row. Record a triple
(column, row, value)for each. - Sort the triples by column, then row, then value.
- Group consecutive triples that share a column, emitting the values in sorted order.
- Return the groups in increasing column order.
Walkthrough
root = [1,2,3,4,5,6,7]
1 col 0, row 0
/ \
2 3 col -1 and +1, row 1
/ \ / \
4 5 6 7 col -2, 0, 0, +2, row 2
triples (column, row, value)
(-2, 2, 4) (-1, 1, 2) (0, 0, 1) (0, 2, 5) (0, 2, 6)
(1, 1, 3) (2, 2, 7)
sorted by column, then row, then value -- the two column-0
row-2 entries order as 5 then 6 by VALUE
groups
col -2: [4]
col -1: [2]
col 0: [1, 5, 6]
col 1: [3]
col 2: [7]
In the drawing 6 is to the left of 5, so a left-to-right rule
would emit [1, 6, 5] here.Complexity
- Time — O(n log n): the traversal is linear and the sort dominates. The sort is unavoidable because the ordering is by value, which no traversal order provides.
- Space — O(n): one triple per node, which dominates. The DFS also costs a call stack of O(h) frames, where h is the tree height — O(log n) when balanced and O(n) on a degenerate one-child-per-level tree, so the worst case is the same O(n) either way.
Common Pitfalls
- Breaking a row-and-column tie by traversal order. That is the sibling problem’s rule, and example 2 distinguishes them.
- Sorting by column and value but not row. Row has to come second, or a deep small value jumps above a shallow large one.
- Grouping by column during the traversal and sorting each group afterwards. Sorting the values alone loses the row, so a deep small value again sorts to the top.
- Forgetting that columns can be negative, and indexing an array by column directly.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def verticalTraversal(self, root):
triples = []
def walk(node, column, row):
if not node:
return
triples.append((column, row, node.val))
walk(node.left, column - 1, row + 1)
walk(node.right, column + 1, row + 1)
walk(root, 0, 0)
triples.sort()
out = []
for column, _row, value in triples:
if out and out[-1][0] == column:
out[-1][1].append(value)
else:
out.append((column, [value]))
return [values for _column, values in out]import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public List<List<Integer>> verticalTraversal(TreeNode root) {
triples = new ArrayList<>();
walk(root, 0, 0);
triples.sort((x, y) -> {
if (x[0] != y[0]) return Integer.compare(x[0], y[0]); if (x[1] != y[1]) return Integer.compare(x[1], y[1]); return Integer.compare(x[2], y[2]);
})
;
List<List<Integer>> out = new ArrayList<>();
Integer lastColumn = null;
for (int[] t : triples) {
if (lastColumn != null && lastColumn == t[0]) out.get(out.size() - 1).add(t[2]);
else {
List<Integer> group = new ArrayList<>();
group.add(t[2]);
out.add(group);
lastColumn = t[0];
}
}
return out;
}
private List<int[]> triples;
private void walk(TreeNode node, int column, int row) {
if (node == null) return;
triples.add(new int[]{column, row, node.val});
walk(node.left, column - 1, row + 1);
walk(node.right, column + 1, row + 1);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<array<int, 3>> triples;
function<void(TreeNode*, int, int)> walk = [&](TreeNode* node, int column, int row) {
if (!node) return;
triples.push_back({column, row, node->val});
walk(node->left, column - 1, row + 1);
walk(node->right, column + 1, row + 1);
};
walk(root, 0, 0);
sort(triples.begin(), triples.end());
vector<vector<int>> out;
bool first = true;
int lastColumn = 0;
for (auto& t : triples) {
if (!first && lastColumn == t[0]) out.back().push_back(t[2]);
else {
out.push_back({t[2]});
lastColumn = t[0];
first = false;
}
}
return out;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @return {number[][]}
*/ var verticalTraversal = function(root) {
const triples = [];
const walk = (node, column, row) => {
if (!node) return;
triples.push([column, row, node.val]);
walk(node.left, column - 1, row + 1);
walk(node.right, column + 1, row + 1);
};
walk(root, 0, 0);
triples.sort((x, y) => x[0] - y[0] || x[1] - y[1] || x[2] - y[2]);
const out = [];
let lastColumn = null;
for (const t of triples) {
if (out.length && lastColumn === t[0]) out[out.length - 1].push(t[2]);
else {
out.push([t[2]]);
lastColumn = t[0];
}
}
return out;
};