DSA AnimatorDSA animations
Binary Tree Right Side View LC #199 Medium BFS · Last Node per Level
Problem

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.

Example 1
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation: From the right: root=1, rightmost at L2=3, rightmost at L3=4.
Example 2
Input: root = [1,2,3,4,null,null,null,5]
Output: [1,3,4,5]
Explanation: Deep left path — node 5 is the only (and rightmost) node at level 4.
Constraints: 0 ≤ nodes ≤ 100  |  −100 ≤ Node.val ≤ 100
Try Examples
Custom:
Approach
BFS + Last Node of Each Level
Standard BFS with level snapshot. For each level, only the LAST polled node (i == sz-1) is visible from the right side. Collect these into the result.
Right Side View
No nodes visible yet…
Binary Tree
Level 1
Level 2
Level 3
Level 4+
In Queue
Processing
Visible 👁
BFS Queue
Queue is empty
Variables
Level #
—
sz (snapshot)
—
i (for loop)
—
result.size
0
Method Call Trace
Step Logic
Press ▶ Play or Next Step to begin the animation.
👁️
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
If root == null return []; else offer root to queue
2
Snapshot sz = queue.size() — number of nodes at current level
3
Poll node: if i == sz-1 → add to result (rightmost!); enqueue non-null children
4
Repeat until queue empty; return result
Time
O(n)
Space
O(n)
Why Last Node = Right Side View

BFS 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.

How to solve Binary Tree Right Side View

LeetCode 199 · Medium · Tree · Pattern: BFS Level Order

Why the obvious approach is slow

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.

The key idea

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.

Remember

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.

More Tree problems