TRT
Sign in
mediumCoreLeetCode#level order#last of each level

Binary tree right side view

Return the values visible from the right side of a tree: the last node of each level.

The Runtime Theory Team1 min read
Taught inLevel-order traversalPro — members onlyVisiting a tree level by level needs a queue instead of a stack. Taking a snapshot of the queue's size separates one level from the next, which solves a family of problems about depth, width and views.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [1, 2, 3, null, 5, null, 4]

out[1, 3, 4]

inroot = [1, 2, 3, 4]

out[1, 3, 4]

inroot = []

out[]

Imagine standing to the right of a binary tree. Return the values of the nodes you can see, from top to bottom.

Before you code

Following right pointers fails on the second example: the right subtree stops at depth 1, and the node seen at depth 2 is 4, in the left subtree. What you see at each depth is that level's last node.

Hints

  1. Do a level-order traversal and record the last value of each level.
  2. Depth-first alternative: visit the right child before the left, and record a node when its depth is reached for the first time.

Production & complexity notes

When solving Binary tree right side view on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Level-order traversal to reinforce the underlying pattern.

What it practices

Per-level processing, from Level-order traversal.

Not started

Sign in to save your learning progress.

Sign in to save