题目描述:
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]
]
采用层序遍历,但是在遍历的过程中需要维护节点的列数,按照根节点的列数等于0为基准。
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
if(root == NULL) return vector<vector<int>>();
queue<pair<TreeNode*, int>> q;
q.push(pair<TreeNode*, int>(root, 0));
unordered_map<int, vector<int>> hash;
while(!q.empty())
{
TreeNode* p = q.front().first;
int i = q.front().second;
q.pop();
if(hash.count(i) == 0) hash[i] = vector<int>(1, p->val);
else hash[i].push_back(p->val);
if(p->left != NULL) q.push(pair<TreeNode*, int>(p->left, i - 1));
if(p->right != NULL) q.push(pair<TreeNode*, int>(p->right, i + 1));
}
int min_i = INT_MAX;
int max_i = INT_MIN;
for(auto x : hash)
{
min_i = min(min_i, x.first);
max_i = max(max_i, x.first);
}
vector<vector<int>> result(max_i - min_i + 1);
for(auto x : hash) result[x.first - min_i] = x.second;
return result;
}
};
本文介绍了一种解决二叉树垂直遍历问题的算法,通过层序遍历并维护节点的列数,实现从上到下、从左到右的节点值返回。示例代码展示了如何使用队列和哈希映射来实现这一过程。

952

被折叠的 条评论
为什么被折叠?



