Total Accepted: 649
Total Submissions: 2309
Difficulty: Medium
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, 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.
Examples:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its vertical order traversal as:
[ [9], [3,15], [20], [7] ]
Given binary tree [3,9,20,4,5,2,7]
,
_3_ / \ 9 20 / \ / \ 4 5 2 7
return its vertical order traversal as:
[ [4], [9], [3,5,2], [20], [7] ]
思路:大致的思路是上来先bfs一遍,存储所有点的坐标。比较需要思考的是,如何在知道坐标的情况下,便捷的生成最后结果。假设每一个TreeNode的坐标都是(row,col),由于最后的结果是按照col来排序的。col相同的情况下,row从上到下,节点从左到右。于是在每一层遍历的时候,我们都可以存入一个map中。map的key是col,value是这一列的所有元素。由于上面的点一定会覆盖下面的点,所以同一列的情况下,越靠近顶越在前面。所以在BFS的时候我们可以放心的把节点存入相应的列的map中。又由于我们是从左到右的遍历,所以row相同情况下,左边一点的节点还是会在前面。
代码如下:
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> result;
if (!root)
return result;
map<int, pair<int, int>> pos;
map<int,vector<int>> mp;
//do bfs to traverse first
queue<TreeNode*> que;
que.push(root);
mp[0].push_back(root->val);
pos[root->val] = make_pair(0, 0);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* cur = que.front();
que.pop();
int x = pos[cur->val].first;
int y = pos[cur->val].second;
if (cur->left) {
que.push(cur->left);
pos[cur->left->val] = make_pair(x + 1, y - 1);
mp[y-1].push_back(cur->left->val);
}
if (cur->right) {
que.push(cur->right);
pos[cur->right->val] = make_pair(x + 1, y + 1);
mp[y+1].push_back(cur->right->val);
}
}
}
//generate result
for (auto &pair : mp) {
result.push_back(pair.second);
}
return result;
}
};