Vertical Order Traversal of a Binary Tree
Vertical Order Traversal of a Binary Tree is a hard trees & bst problem solved with the views pattern.
The best approach, optimal (bfs + column buckets), runs in O(n log n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs + global sort up.
Problem
Given the root of a binary tree, place every node on a grid: the root is at row 0, column 0; a node at (row, col) has its left child at (row + 1, col - 1) and its right child at (row + 1, col + 1).
The vertical order traversal lists the columns from the leftmost to the rightmost. Inside one column, nodes are listed from top to bottom (smaller row first); when two or more nodes share the same row and column, list them in increasing order of value.
Return the traversal as a list of columns, each column being the list of its node values in that order.
Examples
Example 1
- Input
root = [8, 4, 12, 2, 6, 10, 14]- Output
[[2], [4], [8, 6, 10], [12], [14]]- Why
- 6 (row 2, column 0) and 10 (row 2, column 0) share a spot below the root 8 (row 0); rows go first, then the tie at row 2 is broken by value.
Example 2
- Input
root = [5, 9, 3, null, 1, 7]- Output
[[9], [5, 1, 7], [3]]- Why
- 1 is the right child of 9 and 7 is the left child of 3, so both land in column 0 on row 2; 1 < 7 puts 1 first.
Example 3
- Input
root = [4, null, 6, null, 2]- Output
[[4], [6], [2]]- Why
- A right-leaning chain moves one column to the right per level, so each node gets a column of its own.
Constraints
- The tree has
1to1000nodes. 0 <= Node.val <= 1000- The root is at row 0, column 0; a left child is at (row + 1, col - 1) and a right child at (row + 1, col + 1).
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| DFS + global sort | O(n log n) | O(n) |
| Optimal (BFS + column buckets) | O(n log n) | O(n) |
1DFS + global sort
O(n log n)The traversal is O(n); sorting n triples dominates.O(n)n triples plus the recursion stack (height of the tree).Traverse the tree once, recording a triple (column, row, value) for every node. Sort all triples by column, then row, then value, and cut the sorted list into groups of equal column.
- dfs(node, row, col): add (col, row, node.val), recurse on the left child with (row + 1, col - 1) and the right child with (row + 1, col + 1).
- Sort the triples by (col, row, val).
- Walk the sorted list and start a new group whenever the column changes.
class Solution {
public List<List<Integer>> verticalTraversal(TreeNode root) {
List<int[]> items = new ArrayList<>();
dfs(root, 0, 0, items);
items.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
: a[1] != b[1] ? Integer.compare(a[1], b[1]) : Integer.compare(a[2], b[2]));
List<List<Integer>> res = new ArrayList<>();
Integer prevCol = null;
for (int[] it : items) {
if (prevCol == null || it[0] != prevCol) {
res.add(new ArrayList<>());
prevCol = it[0];
}
res.get(res.size() - 1).add(it[2]);
}
return res;
}
private void dfs(TreeNode node, int row, int col, List<int[]> items) {
if (node == null) return;
items.add(new int[] { col, row, node.val });
dfs(node.left, row + 1, col - 1, items);
dfs(node.right, row + 1, col + 1, items);
}
}class Solution:
def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
items = []
def dfs(node: Optional[TreeNode], row: int, col: int) -> None:
if node is None:
return
items.append((col, row, node.val))
dfs(node.left, row + 1, col - 1)
dfs(node.right, row + 1, col + 1)
dfs(root, 0, 0)
items.sort()
res = []
prev_col = None
for col, _, val in items:
if col != prev_col:
res.append([])
prev_col = col
res[-1].append(val)
return resclass Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<array<int, 3>> items;
dfs(root, 0, 0, items);
sort(items.begin(), items.end());
vector<vector<int>> res;
bool first = true;
int prevCol = 0;
for (auto& it : items) {
if (first || it[0] != prevCol) {
res.push_back({});
prevCol = it[0];
first = false;
}
res.back().push_back(it[2]);
}
return res;
}
private:
void dfs(TreeNode* node, int row, int col, vector<array<int, 3>>& items) {
if (node == nullptr) return;
items.push_back({col, row, node->val});
dfs(node->left, row + 1, col - 1, items);
dfs(node->right, row + 1, col + 1, items);
}
};function verticalTraversal(root) {
const items = [];
const dfs = (node, row, col) => {
if (node === null) return;
items.push([col, row, node.val]);
dfs(node.left, row + 1, col - 1);
dfs(node.right, row + 1, col + 1);
};
dfs(root, 0, 0);
items.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
const res = [];
let prevCol = null;
for (const [col, , val] of items) {
if (col !== prevCol) {
res.push([]);
prevCol = col;
}
res[res.length - 1].push(val);
}
return res;
}2Optimal (BFS + column buckets)
O(n log n)BFS is O(n); sorting the buckets costs at most O(n log n) in total and much less when columns are short.O(n)The queue and the buckets each hold up to n entries.Run a level-order traversal carrying each node's (row, column). Drop (row, value) into a bucket for its column and track the smallest column. Columns are contiguous, so the buckets can live in a list indexed by col - minCol. BFS fills each bucket in row order already; only ties inside one bucket need sorting by (row, value), which keeps the sorts small.
- BFS from (root, row 0, col 0); push children with (row + 1, col - 1) and (row + 1, col + 1).
- Put (row, val) into a map col -> list; remember minCol and maxCol.
- For col from minCol to maxCol: sort its list by (row, val) and emit the values.
class Solution {
public List<List<Integer>> verticalTraversal(TreeNode root) {
Map<Integer, List<int[]>> cols = new HashMap<>();
Deque<Object[]> q = new ArrayDeque<>();
q.add(new Object[] { root, 0, 0 });
int minCol = 0, maxCol = 0;
while (!q.isEmpty()) {
Object[] cur = q.poll();
TreeNode node = (TreeNode) cur[0];
int row = (Integer) cur[1], col = (Integer) cur[2];
cols.computeIfAbsent(col, k -> new ArrayList<>()).add(new int[] { row, node.val });
minCol = Math.min(minCol, col);
maxCol = Math.max(maxCol, col);
if (node.left != null) q.add(new Object[] { node.left, row + 1, col - 1 });
if (node.right != null) q.add(new Object[] { node.right, row + 1, col + 1 });
}
List<List<Integer>> res = new ArrayList<>();
for (int c = minCol; c <= maxCol; c++) {
List<int[]> bucket = cols.get(c);
bucket.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
List<Integer> vals = new ArrayList<>();
for (int[] e : bucket) vals.add(e[1]);
res.add(vals);
}
return res;
}
}class Solution:
def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
cols = defaultdict(list)
q = deque([(root, 0, 0)])
min_col = max_col = 0
while q:
node, row, col = q.popleft()
cols[col].append((row, node.val))
min_col = min(min_col, col)
max_col = max(max_col, col)
if node.left:
q.append((node.left, row + 1, col - 1))
if node.right:
q.append((node.right, row + 1, col + 1))
res = []
for c in range(min_col, max_col + 1):
res.append([val for _, val in sorted(cols[c])])
return resclass Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
unordered_map<int, vector<pair<int, int>>> cols;
queue<tuple<TreeNode*, int, int>> q;
q.push({root, 0, 0});
int minCol = 0, maxCol = 0;
while (!q.empty()) {
auto [node, row, col] = q.front();
q.pop();
cols[col].push_back({row, node->val});
minCol = min(minCol, col);
maxCol = max(maxCol, col);
if (node->left) q.push({node->left, row + 1, col - 1});
if (node->right) q.push({node->right, row + 1, col + 1});
}
vector<vector<int>> res;
for (int c = minCol; c <= maxCol; c++) {
auto& bucket = cols[c];
sort(bucket.begin(), bucket.end());
vector<int> vals;
for (auto& e : bucket) vals.push_back(e.second);
res.push_back(vals);
}
return res;
}
};function verticalTraversal(root) {
const cols = new Map();
const q = [[root, 0, 0]];
let head = 0, minCol = 0, maxCol = 0;
while (head < q.length) {
const [node, row, col] = q[head++];
if (!cols.has(col)) cols.set(col, []);
cols.get(col).push([row, node.val]);
minCol = Math.min(minCol, col);
maxCol = Math.max(maxCol, col);
if (node.left !== null) q.push([node.left, row + 1, col - 1]);
if (node.right !== null) q.push([node.right, row + 1, col + 1]);
}
const res = [];
for (let c = minCol; c <= maxCol; c++) {
const bucket = cols.get(c);
bucket.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
res.push(bucket.map((e) => e[1]));
}
return res;
}Edge cases to test
- A single node
- Two nodes on the same row and column: order them by value
- Duplicate values in the same spot
- Fully left- or right-skewed trees (one node per column)
- A node deep in the tree that lands in the root's column
Hints
Hint 1
Give every node a (row, column) coordinate with a simple traversal from the root.
Hint 2
The output order is fully determined by sorting on (column, row, value). Then group consecutive entries with the same column.
Hint 3
A BFS already visits rows in order, so per column you only need to sort entries by (row, value); columns between the leftmost and rightmost one are all non-empty.
FAQ
What is the best time complexity for Vertical Order Traversal of a Binary Tree?
Optimal (BFS + column buckets) runs in O(n log n) time and O(n) extra space. BFS is O(n); sorting the buckets costs at most O(n log n) in total and much less when columns are short.
Which pattern does Vertical Order Traversal of a Binary Tree use?
It is a trees & bst problem that uses the views pattern. Other problems with the same pattern: Top View of Binary Tree, Bottom View of Binary Tree, Left View of Binary Tree.
Is there a brute force solution for Vertical Order Traversal of a Binary Tree?
Yes. DFS + global sort takes O(n log n) time and O(n) space. Traverse the tree once, recording a triple (column, row, value) for every node.
Which edge cases should I test for Vertical Order Traversal of a Binary Tree?
A single node; Two nodes on the same row and column: order them by value; Duplicate values in the same spot; Fully left- or right-skewed trees (one node per column); A node deep in the tree that lands in the root's column.