Imagine standing on the right side of a binary tree. Return the values you can see, from top to bottom.
DSA Animator › DSA Revision › Tree › Binary Tree Right Side View
Remember: the right side view is the last node of every level. Following right children alone is a trap. The video solves Binary Tree Right Side View (LeetCode 199, Medium) with the BFS Level Order pattern from the Tree topic, and you can replay every step in the interactive Binary Tree Right Side View animation.
Imagine standing on the right side of a binary tree. Return the values you can see, from top to bottom.
For the tree 1, with children 2 and 3, where 2 has a right child 5 and 3 has a right child 4, the answer is 1, 3, 4. On each level, you only see the node that is furthest to the right.
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.
Level 0 holds only 1, so 1 is visible. Level 1 holds 2 and 3, and 3 is popped last, so 3 is visible. Level 2 holds 5 and 4. 5 comes from the left subtree, but 4 is popped last, so 4 is visible. The answer is 1, 3, 4. If 3 had no child 4, then 5 would be visible, even though it sits in the left subtree.
In code, loop while the queue is not empty and read the size n. Poll n nodes, pushing their left and right children. When the index equals n minus 1, add that node to the result. It's O of n time and O of the tree width in space.
Remember: the right side view is the last node of every level. Following right children alone is a trap.