Binary Tree Right Side View
Return the values visible from the right side — the last node of each level.
Open on LeetCode ↗02
Intuition
Level order traversal, but keep only each level's final element. Or DFS right-first, recording the first node reached at each new depth — both express 'rightmost per level'.
03
Approach
1
BFS take
Standard level-order; when the per-level loop ends, the last popped value is the visible one.
2
DFS take
Visit right before left, carrying depth. If depth == len(view), this node is the first seen at that depth → rightmost.
3
Pick by constraint
BFS is iterative and obvious; DFS is shorter and O(h) space on balanced trees.
04
Solution & live demo
python
▶1class Solution:
▶2 def rightSideView(self, root):
▶3 view = []
▶4 def dfs(node, depth):
▶5 if not node: return
▶6 if depth == len(view):
▶7 view.append(node.val)
▶8 dfs(node.right, depth + 1) # right first
▶9 dfs(node.left, depth + 1)
▶10 dfs(root, 0)
▶11 return view
05
Edge cases
Left-heavy levels
A left node can be visible if the right subtree is shallower — level-based logic handles it (unlike 'just walk right').
Empty tree
[].
06
Complexity
Time
O(n)
Space
O(h)
Right-first DFS; first arrival per depth wins.