Skip to content

Commit 399cd5d

Browse files
committed
Time: 9 ms (16.40%), Space: 14.8 MB (14.12%) - LeetHub
1 parent b405ea7 commit 399cd5d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
map<int,map<int,multiset<int>>> mp;
16+
17+
void helper(TreeNode* root, int id, int level)
18+
{
19+
if(root)
20+
{
21+
mp[id][level].insert(root->val);
22+
helper(root->left, id-1, level + 1);
23+
helper(root->right, id+1, level + 1);
24+
}
25+
}
26+
27+
vector<vector<int>> verticalTraversal(TreeNode* root) {
28+
29+
int id = 0;
30+
helper(root, id, 0);
31+
32+
vector<vector<int>> ans;
33+
34+
for(auto&[f, s] : mp)
35+
{
36+
vector<int> col;
37+
for(auto& ms : s)
38+
col.insert(col.end(),ms.second.begin(),ms.second.end());
39+
ans.push_back(col);
40+
}
41+
42+
return ans;
43+
44+
}
45+
};

0 commit comments

Comments
 (0)