Rightmost Node

35 min · rightSideView()

A tree can hide most of its branches when you photograph it from the right. At each height, only the node farthest to that side stays visible.

Given the root of a binary tree, return its right-side view — the last node you meet at every depth when that level is read from left to right. List the values from the root downward.

Watch two details:

  • The visible node can come from the left subtree when no node farther right reaches that depth.
  • You return one value per non-empty depth, not every node with a missing right child.
  • An empty tree returns [].

Constraints

  • 0 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000

Hints

Think one level at a time

If you already had all nodes from one depth in left-to-right order, which single position would you keep?

Freeze the queue length

Save the number of queued nodes before processing a level. The node handled at the final index of that group is the one visible from the right.

A depth-first alternative

Visit right children before left children. The first node you reach at a new depth is that depth's rightmost node.

Follow-up

How would the traversal change if you wanted the left-side view instead?

Visible cases

Examples

Example 1

ready
Input
root = [
  1,
  2,
  3,
  null,
  5,
  null,
  4
]
Expected
[
  1,
  3,
  4
]
Why
the last nodes across the three levels are 1, 3, and 4

Example 2

ready
Input
root = []
Expected
[]
Why
an empty tree has no visible nodes

Example 3

ready
Input
root = [
  1,
  2,
  3,
  4,
  null,
  null,
  null,
  5
]
Expected
[
  1,
  3,
  4,
  5
]
Why
the left subtree supplies the view after the right subtree ends

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite