c++的set,multiset,map遍历是有序的。
/*
* @lc app=leetcode id=987 lang=cpp
*
* [987] Vertical Order Traversal of a Binary Tree
*/
// @lc code=start
/**
* 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 {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
map<int, map<int, multiset<int>>> nodes;
traverse(root, 0, 0, nodes);
vector<vector<int>> ans;
for (auto p : nodes) {
vector<int> col;
for (auto q : p.second) {
col.insert(col.end(), q.second.begin(), q.second.end());
}
ans.push_back(col);
}
return ans;
}
private:
void traverse(TreeNode* root, int x, int y, map<int, map<int, multiset<int>>>& nodes) {
if (root) {
nodes[x][y].insert(root -> val);
traverse(root -> left, x - 1, y + 1, nodes);
traverse(root -> right, x + 1, y + 1, nodes);
}
}
};
// @lc code=end
一个超快的方法:
/*
* @lc app=leetcode id=987 lang=cpp
*
* [987] Vertical Order Traversal of a Binary Tree
*/
// @lc code=start
/**
* 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 {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
map<int, vector<int> > m; // when iterate map, key is already the order of x-axis
queue<pair<int, TreeNode*> > q; // for level traversal
q.push(make_pair(0, root)); // root default x-axis is 0
while(!q.empty()) {
multiset<pair<int, int> > tmp; // k: x-axis, v:val Already solved the case when the position is ths same
int len=q.size();
for(int i=0;i<len;++i) {
auto p=q.front();q.pop();
tmp.insert(make_pair(p.first, p.second->val));
if (p.second->left) q.push(make_pair(p.first-1, p.second->left));
if (p.second->right) q.push(make_pair(p.first+1, p.second->right));
}
for(auto p : tmp) m[p.first].push_back(p.second);
}
vector<vector<int> > res;
for(auto kv : m) res.push_back(kv.second);
return res;
}
};
// @lc code=end