Given the root of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom.
root = [1,2,3,null,5,null,4][1,3,4]root = [1,2,3,4,null,null,null,5][1,3,4,5]root == null return []; else offer root to queuesz = queue.size() — number of nodes at current leveli == sz-1 → add to result (rightmost!); enqueue non-null childrenBFS processes nodes left-to-right within each level. By capturing sz = queue.size() before the inner loop, we know exactly how many nodes belong to the current level. The node polled when i == sz - 1 is always the rightmost at that level — exactly what's visible from the right side. This is a simple one-line tweak on top of standard level-order BFS, with no extra data structures needed.
It is tempting to just follow right children from the root. But that fails when a left subtree is deeper, because then a left node is the rightmost one on its level. So we really need the last node of every level.
Run a breadth first search, one level at a time. Within a level, nodes come out of the queue from left to right. So the last node popped in each level is the one visible from the right. Add exactly that node to the answer.
The right side view is the last node of every level. Following right children alone is a trap.
Run the animation above on your own input, or watch the 1:50 video explanation of Binary Tree Right Side View with a dry run and Java code.