Skip to main content

199. Binary Tree Right Side View

medium

Imagine you're standing on the right side of a binary tree — return the values of the nodes you can see, top to bottom. BFS with a last-of-level pick is the cleanest framing.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

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

Input
root = []
Output
[]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

What you 'see' from the right is the last node visited at each level — that's pure level-order BFS.

Hint 2

Snapshot the queue size at the start of each level; the value of the last node popped that round is the answer for that depth.

Hint 3

DFS variant: traverse root, right, left and record the first node encountered at each new depth.

Solution approach

Reveal approach

Level-order BFS picking the last node per level. Initialize queue = [root] (empty return if root is null) and result = []. While queue non-empty: snapshot levelSize. Pop levelSize nodes, enqueueing each one's non-null left then right child. Track the last popped node's value and after the level loop ends, append it to result. Return result. Alternative: DFS visiting right before left, passing depth down — push node.val into result only when result.length == depth (first node seen at that depth is the rightmost in that traversal order). Both are O(n) time, O(h) or O(width) space.

Complexity

Time
O(n)
Space
O(n)

Related patterns

  • tree-bfs
  • tree-dfs
  • queue

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Meta
  • Bloomberg
  • ByteDance

Practice these live with InterviewChamp.AI

Drill Binary Tree Right Side View and Trees problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →