1 题目
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 1:
Input: [3,9,20,null,null,15,7]
3
/\
/ \
9 20
/\
/ \
15 7
Output:
[
[9],
[3,15],
[20],
[7]
]
Examples 2:
Input: [3,9,8,4,0,1,7]
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
Output:
[
[4],
[9],
[3,0,1],
[8],
[7]
]
Examples 3:
Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5)
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2
Output:
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
2 尝试解
2.1 分析
给定一个二叉树,其中任意节点Root的左子节点Left位于其左边一列,右子节点Right位于其右边一列。要求按照从左到右,从上到下的顺序返回每一列节点的值。
即遍历所有二叉树,因为要求从上到下,所以DFS不可,需要用BFS层序遍历。用queue<pair<TreeNode*,int>> layer保存每一个节点及其所在列,用map<int,vector<int>> record由上到下保存每一列节点的值。由于map自动排序,最后遍历map返回结果即可。
2.2 代码
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
map<int,vector<int>> record;
queue<pair<TreeNode*,int>> layer;
vector<vector<int>> result;
if(!root) return result;
layer.push(make_pair(root,0));
while(layer.size()){
record[layer.front().second].push_back(layer.front().first->val);
if(layer.front().first->left)
layer.push(make_pair(layer.front().first->left,layer.front().second-1));
if(layer.front().first->right)
layer.push(make_pair(layer.front().first->right,layer.front().second+1));
layer.pop();
}
for(auto&group : record){
result.push_back(group.second);
}
return result;
}
};
3 标准解
3.1 分析
最小列序min和最大列序max之间一定是连续的,即列总数=max-min+1。所以可以记录最小列序min,最大列序max,然后用unordered_map保存每一列的值。最后从min到max遍历即可。
3.2 代码
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> ans;
if(!root) return ans;
queue<pair<int,TreeNode*>> q;
unordered_map<int, vector<int>> m;
int min = 0, max = 0;
q.push({0, root});
while(!q.empty()) {
int curDist = q.front().first;
TreeNode* curNode = q.front().second;
q.pop();
if(m.find(curDist) == m.end()) {
m[curDist] = vector<int>();
}
m[curDist].push_back(curNode->val);
if(curNode->left) {
q.push({curDist-1, curNode->left});
if(curDist-1 < min) {
min = curDist - 1;
}
}
if(curNode->right) {
q.push({curDist+1, curNode->right});
if(curDist+1 > max) {
max = curDist + 1;
}
}
}
for(int i = min; i <= max; i++) {
ans.push_back(m[i]);
}
return ans;
}
};