← Back to DSA Animator
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.