• 欢迎光临~

# [Oracle] LeetCode 314 Binary Tree Vertical Order Traversal

Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

### Solution

``````/**
* 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<vector<int>> ans;
map<int, map<int, vector<int>> >mp;

void dfs(TreeNode* rt, int row,int col){
if(!rt) return;
mp[col][row].push_back(rt->val);
dfs(rt->left, row+1, col-1);
dfs(rt->right, row+1, col+1);
}

public:
vector<vector<int>> verticalOrder(TreeNode* root) {
dfs(root, 0,0);
for(auto ele:mp){
vector<int> tmp;
for(auto m2:ele.second){
for(auto ele2:m2.second)tmp.push_back(ele2);
}
ans.push_back(tmp);
}
return ans;
}
};
``````