Binary Tree Right Side View

medium

Given the root of a binary tree, imagine standing on its right side. Return the values of the nodes you can see, ordered from top to bottom — that is, the rightmost node at each level.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

The visible node at each level is the rightmost one.
In level-order BFS that's simply the last node dequeued on each level.
A DFS that goes right before left records the first node it reaches at each new depth.

Common doubts

No — if a level's rightmost node lacks a right child, the visible node can descend from a left child; it's the rightmost node, not the right child.
Going right before left, the first node reached at any depth is the rightmost at that depth, so you record on first arrival.
The same idea mirrored: the first node of each level in BFS, or a left-first DFS.

Interview follow-ups

Take the first node of each level in BFS, or recurse left-before-right and record the first node at each depth.
Group nodes by horizontal distance instead of level, keeping the first (top) or last (bottom) node per column.

Fun facts

  • The right-side and left-side views are exact mirrors: swap 'first' and 'last' of each level.
  • Right-first DFS is a neat way to compute the view with O(height) space instead of O(width).

Asked at

AmazonFacebookMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 2, 3, null, 5, null, 4]
Output: [1, 3, 4]
From the right you see 1 (level 0), 3 (level 1), and 4 (level 2).
Example 2
Input: root = [1, null, 3]
Output: [1, 3]
Only the right spine is visible.
Example 3
Input: root = []
Output: []
An empty tree shows nothing.
Constraints

- The number of nodes is in the range [0, 100] - -100 <= Node.val <= 100

Solve this problem →