Practice

Binary Tree Right Side View

Module 17 · Binary Trees

Problem

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 (one value per level: the rightmost node at that level). (LeetCode 199.)

Examples

Example 1

Inputroot = [1,2,3,null,5,null,4]Output[1,3,4]

Explanation. rightmost node per level, top to bottom

text
      1
     / \
    2   3
     \    \
      5    4

Level 1's left child (5) is hidden behind 3 from the right — 3 is farther right at that level, so the answer skips 5.

Constraints

0 ≤ n ≤ 100 nodes

Attempt it first

This looks like a new problem but it's the previous lesson's level-order BFS with one change: instead of collecting every value at a level, keep only the last one processed (the rightmost, if children are enqueued left-before-right). Try adapting your level-order solution before opening anything — or, if you want the alternative framing, think about what a DFS that visits right child before left child would need to track to get the same answer without a queue at all.