1. Collect Tuples and Sort (Flat Tuple Array)
Intuition
Traverse tree with DFS/BFS and collect tuple {col, row, val} for every node. Sort the array with comparator (c1 < c2 || (c1 == c2 && (r1 < r2 || (r1 == r2 && v1 < v2)))). Group adjacent elements with same col.
When to apply: Basic baseline check.
Algorithm
- Step 1: Traverse tree collecting tuples (col, row, val).
- Step 2: Sort tuples array by col asc, row asc, val asc.
- Step 3: Group adjacent elements with same col into sublists.
- Step 4: Return result list.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { struct NodeInfo { int col, row, val; }; void dfs(TreeNode* node, int col, int row, vector<NodeInfo>& nodes) { if (!node) return; nodes.push_back({col, row, node->val}); dfs(node->left, col - 1, row + 1, nodes); dfs(node->right, col + 1, row + 1, nodes); }public: vector<vector<int>> verticalTraversal(TreeNode* root) { vector<NodeInfo> nodes; dfs(root, 0, 0, nodes); sort(nodes.begin(), nodes.end(), [](const NodeInfo& a, const NodeInfo& b) { if (a.col != b.col) return a.col < b.col; if (a.row != b.row) return a.row < b.row; return a.val < b.val; }); vector<vector<int>> res; for (int i = 0; i < nodes.size(); ++i) { if (i == 0 || nodes[i].col != nodes[i - 1].col) { res.push_back({}); } res.back().push_back(nodes[i].val); } return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n log n)— Sorting n tuples takes O(n log n). - Space complexity:
O(n)— Tuple array takes O(n) space.