0%

LeetCode 199. Binary Tree Right Side View

题目

原题在此

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.

Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]

Explanation:

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

解析

使用反向BFS, 先右后左, 在遍历每一层的第一个节点是将此节点值插入vector.

代码

C++

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
/**
* 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 {};
queue<TreeNode*> q;
q.push(root);
vector<int> res;
TreeNode* tmp;
while(!q.empty()) {
res.push_back(q.front() -> val);
int n = q.size();
for(int i = 0; i < n; ++i) {
tmp = q.front();
q.pop();
if(tmp -> right) q.push(tmp -> right);
if(tmp -> left ) q.push(tmp -> left );
}
}
return res;
}
};