question: 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 ; }
target:  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.