Vertical Order Traversal of a Binary Tree

Group nodes by column, breaking ties by row then by value.

Hard
Time O(n log n) Space O(n)
LeetCode
4 min read
tree bfs sorting

Problem#

Assign root column 0. Left child is column c - 1, right is column c + 1. Return columns left-to-right, each containing values sorted by row, ties broken by value.

Examples#

  • [3,9,20,null,null,15,7][[9],[3,15],[20],[7]].
  • [1,2,3,4,5,6,7][[4],[2],[1,5,6],[3],[7]] (1, 5, 6 share column 0; row order then value).

Constraints#

  • 1 <= n <= 1000, 0 <= Node.val <= 1000.

Hints#

Hint 1
Collect tuples (col, row, val) then sort lexicographically.
Hint 2
Group consecutive equal columns to build the output.

Approach#

DFS records every (col, row, val). Sort the vector — natural lexicographic order matches the spec. Walk the sorted list and bucket by column.

Solution#

Vertical Order Traversal of a Binary Tree
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<tuple<int,int,int>> nodes; // (col, row, val)
function<void(TreeNode*,int,int)> dfs = [&](TreeNode* n, int r, int c) {
if (!n) return;
nodes.emplace_back(c, r, n->val);
dfs(n->left, r + 1, c - 1);
dfs(n->right, r + 1, c + 1);
};
dfs(root, 0, 0);
sort(nodes.begin(), nodes.end());
vector<vector<int>> ans;
int prevCol = INT_MIN;
for (auto& [c, r, v] : nodes) {
if (c != prevCol) { ans.push_back({}); prevCol = c; }
ans.back().push_back(v);
}
return ans;
}
};

Editorial#

Storing (col, row, val) in that order lets std::sort do all the tie-breaking with default operator<. Note the spec requires sort-by-value when row and column tie — this differs from older Vertical Order problems and is why we cannot just use BFS-by-column order.

Complexity#

  • Time: O(n log n) dominated by the sort.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.