思路
层序遍历 从左向右遍历每一层取最后一个数,代码如下:
public List<Integer> rightSideView(TreeNode root) {
if (root==null){
return new ArrayList<>();
}
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> list = new ArrayList<>();
TreeNode cur=root;
queue.add(cur);
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
cur = queue.poll();
if (i==size-1){
list.add(cur.val);
}
if (cur.left!=null){
queue.add(cur.left);
}
if (cur.right!=null){
queue.add(cur.right);
}
}
}
return list;
}