Question presented to candidate: "Imagine standing on the right side of a binary tree. Write a Python function that returns, as a list, the values of the nodes you can see, ordered from top to bottom."
What a strong answer should cover:
- The view is the rightmost node of each level โ and it can come from the left subtree when the right side is shorter.
- BFS: level-order traversal with a size snapshot, keeping the last node of each round.
- DFS: visit node, right, left with a depth counter and record a node when depth equals the number of values so far.
- Both are O(n) time; BFS uses O(w) space, DFS O(h).
- Python details:
collections.dequefor O(1)popleft(), andview=Nonerather than a mutable default list in the DFS. - Why "follow the right pointers" is wrong, with a counterexample like [1, 2, 3, 4].
Clarifying questions expected:
- One value per level, top to bottom, and an empty list for an empty tree?
Code / implementation expected: Yes โ right_side_view(root) with a deque-based BFS, plus the DFS alternative, in Python 3.