This solution travels through the whole tree in BFS. For every level, add nodes' children into queue in first-left-then-right order, so the end node of every level is what we want.

```
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Queue<TreeNode> order = new LinkedList<TreeNode>();
if (root == null) return result;
order.offer(root);
while(!order.isEmpty()) {
int count = order.size();
//Every level begins
while(count > 0) {
TreeNode node = order.poll();
if (node.left != null) order.offer(node.left);
if (node.right != null) order.offer(node.right);
if (--count == 0) {
result.add(node.val);
}
}
}
return result;
}
}
```