```
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null)
return ans;
// level order traversal.
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int n = q.size();
while (n-- > 0) {
TreeNode node = q.poll();
if (n == 0) //Last node at the current level, visible from right.
ans.add(node.val);
if (node.left != null)
q.offer(node.left);
if (node.right != null)
q.offer(node.right);
}
}
return ans;
}
```