题目描述:
给定一个二叉树,返回其结点 垂直方向(从上到下,逐列)遍历的值。
如果两个结点在同一行和列,那么顺序则为 从左到右。
示例 1:
输入: [3,9,20,null,null,15,7]
输出:
[
[9],
[3,15],
[20],
[7]
]
示例 2:
输入: [3,9,8,4,0,1,7]
输出:
[
[4],
[9],
[3,0,1],
[8],
[7]
]
示例 3:
输入: [3,9,8,4,0,1,7,null,null,null,2,5](注意:0 的右侧子节点为 2,1 的左侧子节点为 5)
输出:
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
方法1:
主要思路:
(1)使用两个队列的层次遍历,一个队列维护正常的层次遍历,一个队列维护当前结点所在的列的的索引;
(2)将树的列从根节点作为0,开始出发,向左的结点减一,向右的结点加一;
(3)使用unordered_map保存各列索引对应的数据;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
if(root==NULL){
return {};
}
map<int,vector<int>> mp;//保存列的索引对应的数据
queue<int> index;//调整各个结点的列索引
queue<TreeNode*> q;//保存各个结点,用于层次遍历
q.push(root);
index.push(0);
while(!q.empty()){
//获得队列当前的头结点
int tmp_index=index.front();
root=q.front();
index.pop();
q.pop();
//保存到对应的列中
mp[tmp_index].push_back(root->val);
//保存下一层的结点
if(root->left){
q.push(root->left);
index.push(tmp_index-1);
}
if(root->right){
q.push(root->right);
index.push(tmp_index+1);
}
}
//将结果提出
vector<vector<int>>res;
for(auto&it:mp){
res.push_back(it.second);
}
return res;
}
};