What you see from the right of a tree

Trees Mid-level Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Root 1 has a left child 2 (which has a left child 4) and a right child 3. What does the right-hand view show?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 1, 3, 4

Right: row three has only 4, so it is visible from the right.

Each row shows exactly one node from the right, even when it hangs from the left side of the tree.

Why not the others?
  • B 1, 3. Row three still has a node; 4 is the rightmost in that row.
  • C 1, 2, 4. 3 is to the right of 2 in the second row.

30-second answer

Walk the tree row by row with a queue and record the last value in each row. Or run a DFS that visits right children first and records the first node seen at each new depth. Both are O(n) time; the DFS uses O(h) stack.

Practise saying it · 30 s. No recording, just a timer

Explain the right-hand view.

Say your answer out loud, then check which of these points you covered:

  • Last node of each row
  • BFS or right-first DFS
  • O(n)

Deep dive

The DFS version uses O(h) space; the BFS version O(w). Mention the trade-off.

A node on the left can be visible if the right side is shorter.

Left view: take the first value of each row instead.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def right_view(root: Node | None) -> list[int]:
    seen: list[int] = []

    def walk(node: Node | None, depth: int) -> None:
        if node is None:
            return
        if depth == len(seen):
            seen.append(node.val)
        walk(node.right, depth + 1)
        walk(node.left, depth + 1)
    walk(root, 0)
    return seen

Common mistakes

  • Only following right children from the root, which misses left nodes in deeper rows.
  • Recording a value per node instead of per row.

Senior take & follow-ups

Draw a tree whose right side is short to show why 'follow right children' fails.

Follow-up questions

Think of your answer first, then open the hint.

  1. What about the view from the bottom?

    Show hint

    Track horizontal positions (column) with BFS and keep the last value per column.

  2. Can you do it without a queue?

    Show hint

    Yes: DFS right-first, record when depth == len(result).

What each operation costs: Binary Tree · Binary Search Tree · Tree Traversal

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.