链接
题目:
思路:BFS
使用层序遍历,每一个for就是一层;
直接将每一次for循环遍历的最后一个几点保存至List就是结果了;
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> r=new LinkedList<>();
if(root==null) return r;
// bfs
Queue<TreeNode> nodes=new LinkedList<>();
nodes.add(root);
while(!nodes.isEmpty()){
int n=nodes.size();
for(int i=0;i<n;i++){
TreeNode curr=nodes.poll();
if(i==n-1){
r.add(curr.val);
}
if(curr.left!=null){
nodes.add(curr.left);
}
if(curr.right!=null){
nodes.add(curr.right);
}
}
}
return r;
}
}