314. Binary Tree Vertical Order Traversal
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to perform a vertical order traversal of a binary tree. This means we need to group nodes by their column index. The root is at column 0. A node at column c has its left child at column c-1 and its right child at column c+1. The output should be a list of columns, ordered from left to right (smallest column index to largest). Within each column, nodes should be ordered from top to bottom. If two nodes are at the same level in the same column, they should be ordered from left to right.
Solution
Binary Tree Vertical Order Traversal in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution:
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
# Use defaultdict to simplify appending to lists.
column_table = collections.defaultdict(list)
# Queue for BFS, storing (node, column_index) tuples.
queue = collections.deque([(root, 0)])
while queue:
node, column = queue.popleft()
column_table[column].append(node.val)
if node.left:
queue.append((node.left, column - 1))
if node.right:
queue.append((node.right, column + 1))
# Sort columns by their index and create the result list.
# min_col = min(column_table.keys())
# max_col = max(column_table.keys())
# return [column_table[i] for i in range(min_col, max_col + 1)]
# A more Pythonic way is to sort the keys.
return [column_table[col] for col in sorted(column_table.keys())]
Binary Tree Vertical Order Traversal in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
// Map to store nodes column-wise.
Map<Integer, List<Integer>> columnTable = new HashMap<>();
// Queue for BFS. Using AbstractMap.SimpleEntry as a Pair.
Queue<AbstractMap.SimpleEntry<TreeNode, Integer>> queue = new ArrayDeque<>();
int minCol = 0, maxCol = 0;
queue.offer(new AbstractMap.SimpleEntry<>(root, 0));
while (!queue.isEmpty()) {
AbstractMap.SimpleEntry<TreeNode, Integer> p = queue.poll();
TreeNode node = p.getKey();
int column = p.getValue();
// Add node value to the list for its column.
columnTable.computeIfAbsent(column, k -> new ArrayList<>()).add(node.val);
// Update min and max column indices.
minCol = Math.min(minCol, column);
maxCol = Math.max(maxCol, column);
if (node.left != null) {
queue.offer(new AbstractMap.SimpleEntry<>(node.left, column - 1));
}
if (node.right != null) {
queue.offer(new AbstractMap.SimpleEntry<>(node.right, column + 1));
}
}
// Construct the result from the map, in order of columns.
for (int i = minCol; i <= maxCol; i++) {
if (columnTable.containsKey(i)) {
result.add(columnTable.get(i));
}
}
return result;
}
}
Binary Tree Vertical Order Traversal in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> result;
if (!root) {
return result;
}
// Map to store nodes column-wise. std::map keeps keys sorted.
map<int, vector<int>> columnTable;
// Queue for BFS, storing pairs of {node, column_index}
queue<pair<TreeNode*, int>> q;
q.push({root, 0});
while (!q.empty()) {
pair<TreeNode*, int> p = q.front();
q.pop();
TreeNode* node = p.first;
int column = p.second;
columnTable[column].push_back(node->val);
if (node->left) {
q.push({node->left, column - 1});
}
if (node->right) {
q.push({node->right, column + 1});
}
}
// Extract values from map into the result vector.
// Since std::map is sorted by key, the columns will be in order.
for (auto const& [column, values] : columnTable) {
result.push_back(values);
}
return result;
}
};
Binary Tree Vertical Order Traversal in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function verticalOrder(root: TreeNode | null): number[][] {
if (!root) {
return [];
}
const columnMap = new Map<number, number[]>();
const queue: [TreeNode, number][] = [[root, 0]];
let minCol = 0;
let maxCol = 0;
while (queue.length > 0) {
const [node, col] = queue.shift()!;
if (!columnMap.has(col)) {
columnMap.set(col, []);
}
columnMap.get(col)!.push(node.val);
minCol = Math.min(minCol, col);
maxCol = Math.max(maxCol, col);
if (node.left) {
queue.push([node.left, col - 1]);
}
if (node.right) {
queue.push([node.right, col + 1]);
}
}
const result: number[][] = [];
for (let i = minCol; i <= maxCol; i++) {
if (columnMap.has(i)) {
result.push(columnMap.get(i)!);
}
}
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.