难度:困难。
标签:二叉树,深度优先搜索,广度优先搜索,哈希表。
使用哈希表来记录col,row和val的信息,然后可以使用深搜或广搜来得到这些信息,之后需要对得到的信息进行排序。
正确解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
static bool cmp(pair<int, int>& a, pair<int, int>& b){
if(a.first == b.first){
return a.second < b.second;
}
return a.first < b.first;
}
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<vector<int>> ans;
// map<col, vector<row, val>>
map<int, vector<pair<int, int>>> maps;
queue<TreeNode*> node_que;
queue<pair<int, int>> index_que;
node_que.push(root);
index_que.push({0, 0});
while(!node_que.empty()){
int size = node_que.size();
for(int i = 0; i < size; ++i){
TreeNode* cur = node_que.front();
node_que.pop();
auto pair = index_que.front();
index_que.pop();
int row = pair.first, col = pair.second;
maps[col].push_back({row, cur->val});
if(cur->left != nullptr){
node_que.push(cur->left);
index_que.push({row + 1, col - 1});
}
if(cur->right != nullptr){
node_que.push(cur->right);
index_que.push({row + 1, col + 1});
}
}
}
for(auto it = maps.begin(); it != maps.end(); it++){
// cout << (*it).first << endl;
sort((*it).second.begin(), (*it).second.end(), cmp);
vector<int> temp;
for(auto& p:(*it).second){
temp.emplace_back(p.second);
}
ans.emplace_back(temp);
}
return ans;
}
};
结果: