-
Notifications
You must be signed in to change notification settings - Fork 0
/
987. Vertical Order Traversal of a Binary Tree.c
56 lines (47 loc) · 1.5 KB
/
987. Vertical Order Traversal of a Binary Tree.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/** C++
* 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:
void traverse(map<int, map<int, vector<int>>>& mp, int level, int dist, TreeNode* root)
{
mp[dist][level].push_back(root->val);
if(root->left)
{
traverse(mp, level+1, dist-1, root->left);
}
if(root->right)
{
traverse(mp, level+1, dist+1, root->right);
}
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
map<int, map<int, vector<int>>> mp;
map<int, map<int, vector<int>>>::iterator mit;
map<int, vector<int>>::iterator it;
vector<vector<int>> res;
traverse(mp, 0, 0, root);
for (mit = mp.begin(); mit != mp.end(); mit++)
{
vector<int> tmp;
for(it = (mit->second).begin(); it != (mit->second).end(); it++)
{
sort((it->second).begin(), (it->second).end());
for (auto i: it->second)
{
tmp.push_back(i);
}
}
res.push_back(tmp);
}
return res;
}
};