[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
我们用 \(map\) 套 \(map\) 套 \(vector\) 来储存每个 \(row, col\) 的节点值,因为对于左节点等价于: \(row+1, col-1\).
那么我们对树进行 \(DFS\), 然后再对 \(map\) 进行遍历即可
点击查看代码
/**
* 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;
}
};