179/670

179. Binary Tree Right Side View

Medium

You receive the root of a binary tree. Imagine standing off to the tree's right side and looking straight at it: on every level, the node nearest to you blocks all the others, so you see exactly one node per depth — the rightmost node of that level.

Return the values of the visible nodes as a list ordered from the top level down to the deepest level.

Note that a visible node is not always on a chain of right children — if the right subtree is shallower than the left, deeper levels are 'seen' from the left subtree.

What the right side seesGold nodes are the ones visible from the right: one per level. Node 4 hides 5, and 3 hides 2.
12354viewer looks in from the right

Example 1:

Input: root = [1, 2, 3, null, 5, null, 4]

Output: [1, 3, 4]

Explanation: Level 0 shows the root 1, level 1 shows 3 (it hides 2), and level 2 shows 4 (it hides 5).

Example 2:

Input: root = [1, 2, 3, 4, null, null, null, 5]

Output: [1, 3, 4, 5]

Explanation: The right subtree stops at depth 1, so the nodes visible at depths 2 and 3 (4 and 5) both come from the left subtree.

Constraints:

  • 1 ≤ number of nodes ≤ 100
  • -100 ≤ node value ≤ 100

Hints:

Breadth-first search visits the tree level by level. If you process one whole level per loop iteration, the last node you dequeue on that level is exactly the one visible from the right.

There is also a depth-first trick: traverse the tree visiting the RIGHT child before the left, and record a node's value whenever you arrive at a depth you have never reached before — the first node encountered at each depth is the rightmost one.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: root = [1, 2, 3, null, 5, null, 4]

Expected output: [1, 3, 4]