-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
75 lines (65 loc) · 1.83 KB
/
main.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
/**
* 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<int> rightSideView(TreeNode* root) {
if (!root) return {};
vector<int> result = {root->val};
vector<TreeNode*> q = {root};
while (true) {
vector<TreeNode*> new_q;
for (TreeNode* u : q) {
if (u->left) new_q.push_back(u->left);
if (u->right) new_q.push_back(u->right);
}
if (new_q.empty()) break;
result.push_back(new_q.back()->val);
q = move(new_q);
}
return result;
}
};
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
function<void(TreeNode*, int)> dfs = [&](TreeNode* u, int d) -> void {
if (!u) return;
if (d == result.size()) result.push_back(u->val);
dfs(u->right, d + 1);
dfs(u->left, d + 1);
};
dfs(root, 0);
return result;
}
};
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
queue<pair<TreeNode*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto [u, d] = q.front();
q.pop();
if (!u) continue;
if (d < result.size())
result[d] = u->val;
else
result.push_back(u->val);
q.push({u->left, d + 1});
q.push({u->right, d + 1});
}
return result;
}
};