题目描述
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。\
解题思路
清楚BFS遍历的模板,根据题目的意思是获取树的右视图,关键在于写出i=size-1条件
AC 代码
public class Solution {
public List<Integer> rightSideView(TreeNode root){
List<Integer> list=new ArrayList<>();
if(root==null){
return list;
}
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
int size=q.size();
for(int i=0;i<size;i++){
TreeNode cur=q.poll();
if(cur.left!=null){
q.offer(cur.left);
}
if(cur.right!=null){
q.offer(cur.right);
}
if(i==size-1){
list.add(cur.val);
}
}
}
return list;
}
}
总结
要多刷题