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
- Do a level-order traversal and record the last value of each level.
- 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.