Binary Tree Vertical Order Traversal
Medium
Topics
Given the root of a binary tree, return the vertical order traversal of its node values.
Assign the root column 0. A left child sits one column to the left of its parent, a right child one column to the right. Group the nodes by column and return the groups ordered from the leftmost column to the rightmost.
Within a column, nodes appear top to bottom, and two nodes on the same row appear left to right.
On this judge the columns are shown separated by |.
Example 1
[[9],[3,15],[20],[7]].null marks a missing child.Input: root = [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Column -1 holds 9; column 0 holds 3 and, one row down, 15; column 1 holds 20; column 2 holds 7.
Example 2
Input: root = [3,9,8,4,0,1,7] Output: [[4],[9],[3,0,1],[8],[7]] Explanation: Three nodes land in column 0: the root, plus 0 and 1 which come back in from opposite sides.
Example 3
Input: root = [1] Output: [[1]] Explanation: A single node occupies column 0 alone.
Constraints
- 0 <= number of nodes <= 100
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
The column of a node is fully determined by the path taken to reach it: start at 0, subtract one for every left step, add one for every right step. So the column can be carried down with the node, and no geometry has to be reconstructed afterwards.
The ordering rule is the part that catches people out. Two different columns can send nodes back into the same column — in example 2 the root, the right child of 9, and the left child of 8 all land in column 0 — and they must come out top-to-bottom, then left-to-right.
A breadth-first walk delivers exactly that order for free: it visits row by row, and within a row left to right. Appending to each column’s bucket as nodes are visited therefore fills every bucket in the required order, with no sorting of nodes needed. Only the columns have to be sorted at the end.
Approach
- Walk the tree breadth-first, carrying each node’s column alongside it. Push the root with column 0.
- Append every visited node’s value to the bucket for its column.
- Enqueue the left child at
column - 1and the right child atcolumn + 1. - When the walk finishes, read the buckets out in increasing column order.
Walkthrough
root = [3,9,20,null,null,15,7]
3 col 0
/ \
9 20 col -1, col 1
/ \
15 7 col 0, col 2
visit order (breadth-first) and the bucket each lands in
3 -> col 0 buckets: {0: [3]}
9 -> col -1 buckets: {-1: [9], 0: [3]}
20 -> col 1 buckets: {-1: [9], 0: [3], 1: [20]}
15 -> col 0 buckets: {-1: [9], 0: [3,15], 1: [20]}
7 -> col 2 buckets: {-1: [9], 0: [3,15], 1: [20], 2: [7]}
columns in order -1, 0, 1, 2
answer [[9],[3,15],[20],[7]]Complexity
- Time — O(n log n): each node is visited once; the log factor is sorting the distinct column keys, of which there are at most n.
- Space — O(n): the queue plus one stored value per node across the buckets.
Common Pitfalls
- Walking the tree depth-first and appending as you go. A depth-first walk reaches a deep left node before a shallow right one, so a column fed by both comes out in the wrong order — example 2’s middle column would read 3, 1, 0 instead of 3, 0, 1.
- Sorting each column’s values. The order is positional, not numeric; sorting example 1’s middle column would give 3, 15 by luck and break on negative values.
- Returning the buckets in insertion order rather than by column. Insertion order follows the traversal, so it starts at column 0 rather than the leftmost.
- Forgetting the empty tree, which has no columns at all.
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 verticalOrder(self, root):
if not root:
return []
buckets = {}
q = [(root, 0)]
i = 0
while i < len(q):
node, col = q[i]
i += 1
buckets.setdefault(col, []).append(node.val)
if node.left:
q.append((node.left, col - 1))
if node.right:
q.append((node.right, col + 1))
return [buckets[c] for c in sorted(buckets)]import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
if (root == null) return out;
Map<Integer, List<Integer>> buckets = new TreeMap<>();
Deque<Object[]> q = new ArrayDeque<>();
q.add(new Object[]{root, 0});
while (!q.isEmpty()) {
Object[] cur = q.poll();
TreeNode node = (TreeNode) cur[0];
int col = (Integer) cur[1];
buckets.computeIfAbsent(col, x -> new ArrayList<>()).add(node.val);
if (node.left != null) q.add(new Object[]{node.left, col - 1});
if (node.right != null) q.add(new Object[]{node.right, col + 1});
}
out.addAll(buckets.values());
return out;
}
}#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>> verticalOrder(TreeNode* root) {
vector<vector<int>> out;
if (!root) return out;
map<int, vector<int>> buckets;
queue<pair<TreeNode*, int>> q;
q.push({root, 0});
while (!q.empty()) {
pair<TreeNode*, int> cur = q.front();
q.pop();
buckets[cur.second].push_back(cur.first->val);
if (cur.first->left) q.push({cur.first->left, cur.second - 1});
if (cur.first->right) q.push({cur.first->right, cur.second + 1});
}
for (auto& kv : buckets) out.push_back(kv.second);
return out;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @return {number[][]}
*/ var verticalOrder = function(root) {
if (!root) return [];
const buckets = new Map();
const q = [[root, 0]];
for (let i = 0; i < q.length; i++) {
const node = q[i][0], col = q[i][1];
if (!buckets.has(col)) buckets.set(col, []);
buckets.get(col).push(node.val);
if (node.left) q.push([node.left, col - 1]);
if (node.right) q.push([node.right, col + 1]);
}
return [...buckets.keys()].sort((a, b) => a - b).map(c => buckets.get(c));
};