Given the root of a binary tree, return the values visible when looking at the tree from the right side, ordered from top to bottom.
Example
Input root = [1,2,3,null,5,null,4]
Output [1,3,4]
Key Pointers
This is level order traversal with one twist: only the last node visited at each level matters.
BFS visits nodes left-to-right within a level, so the last one popped in a level is the rightmost.
A DFS that always visits the right child before the left, recording a value only the first time a new depth is reached, works too.
Step-by-Step Analysis
If root is None, return [].
BFS level by level, same pattern as Level Order Traversal.
At the end of processing each level, append the value of the last node dequeued in that level to result.
Return result once the queue is empty.
Complexity
Time: O(n) — Space: O(n)
Code
from collections import deque
def rightSideView(root: TreeNode | None) -> list[int]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
if i == level_size - 1:
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
Code Explanation
How the solution above works, piece by piece.
Breadth-first search level by level, exactly like Level Order Traversal.
level_size = len(queue) fixes how many nodes belong to the current level.
i == level_size - 1 is the last (rightmost) node of the level: record it.
Children are queued left then right, so the last node popped in each level is the rightmost one.
O(n) time, O(width) queue.
Visual Walkthrough
Running it on root = [1, 2, 3, null, 5, null, 4]:
Looking from the right you see the last node of each level. The BFS visits every level left to right, and i == level_size - 1 picks that last node: [1, 3, 4]. Note 5 is hidden behind 4.