/**
* 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 {
private:
vector<tuple<int, int, int>> nodes;
void dfs(TreeNode* root, int row, int column) {
if (!root) return;
nodes.emplace_back(column, row, root->val);
dfs(root->left, row + 1, column - 1);
dfs(root->right, row + 1, column + 1);
}
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
dfs(root, 0, 0);
sort(nodes.begin(), nodes.end());
vector<vector<int>> res;
int prevColumn = INT_MIN;
for (const auto& [column, _, value] : nodes) {
if (column != prevColumn) {
prevColumn = column;
res.emplace_back();
}
res.back().emplace_back(value);
}
return res;
}
};