Binary Tree Right Side View
Given a binary tree, imagine yourself standing on therightside 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]
.
Tips:
简单的BFS,需要注意要将一层中的所有点都加入queue而不是只加最右边的那个点。先右后左。
Code:
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode curt = queue.poll();
if (curt.right != null) queue.offer(curt.right);
if (curt.left != null) queue.offer(curt.left);
if (i == 0) res.add(curt.val);
}
}
return res;
}
}