SDE & MLE Prep

199. Binary Tree Right Side View

Problem

Imagine standing to the right of a binary tree. Return the values you can see, from top to bottom: the rightmost node of each level.

Example: [1,2,3,null,5,null,4] → [1,3,4]; [1,2,3,4] → [1,3,4]

Level-order BFS; the last node of each level is visible from the right. (DFS alternative: visit right first, record first node at each new depth.)

Complexity: O(n).

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        res, q = [], deque([root] if root else [])
        while q:
            res.append(q[-1].val)
            for _ in range(len(q)):
                node = q.popleft()
                if node.left: q.append(node.left)
                if node.right: q.append(node.right)
        return res