Problem Statement
Binary Tree Right Side View
Picture a binary tree. A binary tree is a structure where each box, called a node, holds a value and can point to up to two child boxes below it, one on the left and one on the right. Now imagine you walk around to the right side of the tree and look at it straight on. From that angle, at each horizontal level you can only see one node, the one furthest to the right that is not hidden behind another. Your job is to return those visible values, listed from the top of the tree down to the bottom.
Signals to notice
Brute force first
Full level order traversal, take last element of each level — but stores all nodes per level unnecessarily. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
BFS: at each level, only record the last node processed. You already know the level size from the queue — the last node in each batch is the right side view. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on root = [1,2,3,null,5,null,4] (level 1: 2,3; level 2: 5 under 2, 4 under 3)
init: queue=[1], result=[] level 0 (size=1): pop 1, i==last -> result=[1]; enqueue 2,3 -> queue=[2,3] level 1 (size=2): pop 2 (not last, enqueue 5); pop 3 i==last -> result=[1,3]; enqueue 4 -> queue=[5,4] level 2 (size=2): pop 5 (not last); pop 4 i==last -> result=[1,3,4]; no children -> queue=[] queue empty -> stop return [1,3,4]
What must stay true
The right side view is exactly the last node at each depth level. BFS with level-size tracking naturally identifies this node. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
queue <- [root]; result <- []
while queue not empty:
size <- len(queue) # nodes on this level
for i in 0..size-1:
node <- queue.popleft()
if i == size-1: result.append(node.val) # last = rightmost
enqueue node.left, node.right (if present)
return resultPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Thinking you need DFS right-first traversal — that works too, but BFS is more intuitive. With DFS, you must visit the right child first and only record the first node seen at each new depth. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.