-
Notifications
You must be signed in to change notification settings - Fork 0
/
vertical-order-traversal-of-a-binary-tree.cpp
45 lines (45 loc) · 1.25 KB
/
vertical-order-traversal-of-a-binary-tree.cpp
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
/**
* 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>> res;
vector<vector<int>> c;
void dfs(TreeNode* root, int x, int y) {
if (!root)
return;
c.push_back({root->val, x, y});
dfs(root->left, x - 1, y + 1);
dfs(root->right, x + 1, y + 1);
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
dfs(root, 0, 0);
sort(c.begin(), c.end(), [](auto v1, auto v2) {
if (v1[1] == v2[1]) {
if (v1[2] == v2[2]) {
return v1[0] < v2[0];
}
return v1[2] < v2[2];
}
return v1[1] < v2[1];
});
int xPrev = INT_MIN;
for (auto v : c) {
if (v[1] != xPrev) {
res.push_back({v[0]});
xPrev=v[1];
}
else res.back().push_back(v[0]);
}
return res;
}
};