binary-tree
breadth-first-search

Given the root of a binary tree, imagine standing on the right side of it. Return the values of the nodes you can see, ordered from top to bottom — that is, the last (rightmost) node visited at each level.

Input / output

  • Input: root: TreeNode (JSON test fixture is a LeetCode-style level-order array, e.g. [1,2,3,null,5,null,4], with null for a missing child)
  • Output: int[]

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= node value <= 100

Follow-up

Can you solve it with a single recursive DFS pass (visiting right children before left, recording the first node seen at each depth) instead of a level-by-level BFS?

Examples

Example 1

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

Example 2

Input: root = [1,null,3]
Output: [1,3]

Example 3 (empty tree)

Input: root = []
Output: []
🔒 6 hidden

Running will execute all 9 cases, including 6 hidden ones.