Skip to the solution
MediumDSA11 min read

How do you get the right-side view of a binary tree?

791 views

The problem

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.deque for O(1) popleft(), and view=None rather 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.

  • trees
  • bfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBFS: last node of every level (6 trees)
PythonBFS vs DFS, left view, and the right-pointer trap on 200 trees

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 66 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is a monotonic stack and when do you use it?

Continue