public List<Integer> rightSideView(TreeNode root){
  if (root == null) {
    return null;
  }
  List<Integer> res=new ArrayList<>();
  Queue<TreeNode> queue=new ArrayDeque<>();
  queue.offer(root);
  while (!queue.isEmpty()) {
    int size=queue.size();
    for (int i=0; i < size; i++) {
      TreeNode node=queue.poll();
      if (node.left != null) {
        queue.offer(node.left);
      }
      if (node.right != null) {
        queue.offer(node.right);
      }
      if (i == size - 1) {
        res.add(node.val);
      }
    }
  }
  return res;
}

public List < Integer > rightSideView ( TreeNode root ) { if ( root == null ) { return null ; } List < Integer > res = new ArrayList < > ( ) ; Queue < TreeNode > queue = new ArrayDeque < > ( ) ; queue . offer ( root ) ; while ( ! queue . isEmpty ( ) ) { int size = queue . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { TreeNode node = queue . poll ( ) ; if ( node . left != null ) { queue . offer ( node . left ) ; } if ( node . right != null ) { queue . offer ( node . right ) ; } if ( i == size - 1 ) { res . add ( node . val ) ; } } } return res ; }
bfs . do a level order traversal with queue . for each level , traverse each node and add children to the queue . if it ' s at the end of current level , add node ' s value to result . < p > easy to understand , but queue . poll ( ) and queue . offer ( ) can be slow .
