You can do this with either BFS or DFS. BFS goes level by level so it’s natural for this:
We can then do the level by level traversal while replacing the last node we see in each level and return the last number for each level.
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
q = deque()
q.append(root)
res = defaultdict(int)
l = -1
while q:
l += 1
for _ in range(len(q)):
node = q.popleft()
if not node:
continue
res[l] = node.val
q.append(node.left)
q.append(node.right)
return [res[i] for i in range(l)]