0%

199. Binary Tree Right Side View

bfs O(n) time O(n) space
bfs逐层遍历每次取最后一个即可

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
if (!root) return {};
vector<int> res;
list<TreeNode *> q; // q{{root}};
q.push_back(root);
while (!q.empty()) {
res.push_back(q.back()->val);
for (int i = q.size(); i > 0; --i) {
auto p = q.front(); q.pop_front();
if (p->left) { // 因为要直接access node一定不能把nullptr放进去
q.push_back(p->left);
}
if (p->right) {
q.push_back(p->right);
}
}
}
return res;
}
};