Skip to main content

Vertical Order Traversal of a Binary Tree

Problem

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

Solution Approach

Expected Time complexity: O(n)O(n)

Click - to see solution code
class Solution {
map<int, map<int, vector<int>>> mp;

public:
void traverse(TreeNode* root, int c, int r) {
if (!root) return;
mp[c][r].push_back(root->val);
traverse(root->left, c - 1, r + 1);
traverse(root->right, c + 1, r + 1);
}

vector<vector<int>> verticalTraversal(TreeNode* root) {
traverse(root, 0, 0);
vector<vector<int>> ans;
for (auto i : mp) {
vector<int> v;
for (auto j : i.second) {
sort(j.second.begin(), j.second.end());
for (auto k : j.second) v.push_back(k);
}
ans.push_back(v);
}
return ans;
}
};