Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

1
2
3
4
5
1 <---
/ \
2 3 <---
\ \
5 4 <---

You should return [1, 3, 4].

思路

利用层次遍历(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
32
33
34
35
36
37
38
39
40
41
/**
* 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) {
vector<int> ans;
queue<TreeNode*> bfs;
if(root != NULL){
bfs.push(root);
bfs.push(NULL);
int tmp = 0;
while(!bfs.empty()){
TreeNode* cur = bfs.front();
bfs.pop();
if(cur != NULL){
tmp = cur->val;
if(cur->left != NULL){
bfs.push(cur->left);
}
if(cur->right != NULL){
bfs.push(cur->right);
}
}
else{
ans.push_back(tmp);
tmp = 0;
if(!bfs.empty()) bfs.push(NULL);
}
}
}
return ans;
}
};