题目:
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 7return its vertical order traversal as:
[ [9], [3,15], [20], [7] ]
- Given binary tree
[3,9,8,4,0,1,7],
3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7return its vertical order traversal as:
[ [4], [9], [3,0,1], [8], [7] ]
- Given binary tree
[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 2return its vertical order traversal as:
[ [4], [9,5], [3,0,1], [8,2], [7] ]
思路:
这道题目的基本思路是比较明显的,即首先构造一个map,其key值为在竖直方向上的位置,value则是在该位置上的所有结点值。然后在遍历树的过程中填充该map。这道题目的一个坑就是:我开始用了DFS,但是后来发现会导致同一竖直层中元素的顺序不对(例如最后一个例子中的倒数第二行[8,2]用DFS会形成[2,8])。所以正确的解法是采用BFS。
代码:
/**
* 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;
vector<vector<int>> ret;
queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
while(!q.empty()) {
TreeNode* node = q.front().first;
int index = q.front().second;
q.pop();
mp[index].push_back(node->val);
if(node->left) {
q.push(make_pair(node->left, index - 1));
}
if(node->right) {
q.push(make_pair(node->right, index + 1));
}
}
for(auto it = mp.begin(); it != mp.end(); ++it) {
ret.push_back(it->second);
}
return ret;
}
};
这篇博客详细介绍了LeetCode 314题——二叉树垂直遍历的解题过程。博主通过一个例子展示了如何利用BFS(广度优先搜索)来正确解决这个问题,指出使用DFS(深度优先搜索)可能导致同一竖直层节点顺序错误的问题,并给出了相应的正确代码实现。
321

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



