Leetcode解题: Binary Tree Right Side View (199)

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 <—
\ \
5 4 <—
You should return [1, 3, 4].

解法1: BFS, O(N)

这题也是考察BFS算法的一个变形,题意是要求每一层最右边的node。那么我们按层遍历,对于每一层只取第一个(最右边)的node的数值就可以了。
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
33
34
35
36
37
38
/**
* 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> res;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int k = q.size();
for (int i = 0; i < k; ++i) {
TreeNode* cur = q.front();
if (i == 0) {
res.push_back(cur->val);
}
q.pop();
if (cur->right) {
q.push(cur->right);
}
if (cur->left) {
q.push(cur->left);
}
}
}
return res;
}
};

Java

1