Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Trees

Binary Tree Right Side View

MEDIUM✓ CHIP-TIMEDLC #199 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Stand to the right of the tree and list every node you can actually see — one value per depth, whichever node is furthest right at that floor.

A binary tree arrives, and the task is to list exactly what you'd see standing to the right of it and looking straight across — one value per depth level, whichever node sits furthest to the right at that level.

A level can lean entirely left with nothing on its right side at all, and the node furthest right that's still visible from outside at that depth is still the one that counts, even when it's the only node on that level.

An empty tree produces an empty list, since there's no depth at all to report a rightmost node for.

  • the tree can hold anywhere from zero to a few thousand nodes
  • node values can be negative, zero, or positive
  • exactly one value is reported per depth level, ordered root-level first downward
EX 01
root = []
→ []
empty tree
EX 02
root = [1]
→ [1]
single node
EX 03
root = [1, 2, 3, null, 5, null, 4]
→ [1, 3, 4]
left child peeks through a gap

The hintstake only what you need

HINT 1 THE NUDGE

You need exactly one value per depth: the rightmost node reachable at that depth, even if the tree leans left there.

HINT 2 THE STRUCTURE

If you visit right children before left ones, the FIRST node you ever reach at a new depth is guaranteed to be that depth's rightmost node.

HINT 3 ONE STEP FROM THE ANSWER

DFS(node, depth): if depth equals the answer list's current length, this is the first arrival at that depth — record it. Then recurse right before left.

Coach's boardthe pattern, step by step

STANDING ON THE RIGHTPATTERN · RIGHT-FIRST DFSroot = [1, 2, 3, null, 5, null, 4]
STEP 1

Visit right child before left, and record a depth only the FIRST time it's reached — that first arrival is always the rightmost node.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/binary-tree-right-side-view.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        result: List[int] = []

        def dfs(node: Optional[TreeNode], depth: int) -> None:
            if not node:
                return
            if depth == len(result):     # first arrival at this depth
                result.append(node.val)
            dfs(node.right, depth + 1)   # right first, so it wins the "first arrival"
            dfs(node.left, depth + 1)

        dfs(root, 0)
        return result
TIME O(N)SPACE O(H)PYTHON · RACE PACE · 14 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED