-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path987+Vertical Order Traversal of a Binary Tree.cpp
85 lines (70 loc) · 2.02 KB
/
987+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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 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 dfs(TreeNode* root, int x, int y) {
if (root == nullptr) return;
dfs(root->left, x - 1, y + 1);
vecs.emplace_back(x, y, root->val);
dfs(root->right, x + 1, y + 1);
return;
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
dfs(root, 0, 0);
sort(vecs.begin(), vecs.end());
vector<vector<int>> res;
int lastX = INT_MIN;
for (auto const &[x, y, val] : vecs ) {
if (x != lastX) {
lastX = x;
res.emplace_back();
}
res.back().push_back(val);
}
return res;
}
private:
vector<tuple<int, int, int>> vecs;
};
const int maxn = 1e3 + 5;
class Solution {
public:
struct Node {
int val;
int x;
int y;
} matN[maxn];
void dfs(TreeNode* root, int x, int y) {
if (root == nullptr) return;
dfs(root->left, x - 1, y + 1);
matN[idx++] = {root->val, x, y};
dfs(root->right, x + 1, y + 1);
return;
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
idx = 0;
dfs(root, 0, 0);
vector<vector<int>> res;
int lastX = INT_MIN;
for (int i = 0; i < idx; i++) {
cout << matN[idx].val << " " << matN[idx].x << " " << matN[idx].y << endl;
if (matN[i].x != lastX) {
lastX = matN[i].x;
res.emplace_back();
}
res.back().push_back(matN[i].val);
}
return res;
}
private:
int idx;
};