InterviewPrepKit

Home / Coding / Trees

Binary Tree Right Side View

medium Original β†—
Solving tips
  • Reframe as 'the rightmost node of every level', which is the last node dequeued in a BFS level (capture it at i == level_size - 1).
  • Snapshot level_size before the inner loop since the queue grows as you enqueue children.
  • Slick DFS alternative: recurse right child before left and record a node only when depth == len(view), so the first node seen per depth is the rightmost.
  • A node with only a left child can still be its level's rightmost; both approaches handle it. Target O(n) time, O(n)/O(h) space.

Problem

You are given the root of a binary tree. Imagine standing to the right of the tree and looking left. Return the values of the nodes you can see, ordered from top to bottom.

In other words, for each depth level of the tree, the visible node is the rightmost one at that level. Return one value per level.

Examples

Example 1

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

Level 0: 1. Level 1: nodes 2,3 β€” rightmost is 3. Level 2: nodes 5,4 β€” rightmost is 4.

Example 2

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

The root 1 has only a right child 3; both are visible from the right.

Example 3

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

Level 0: 1. Level 1: 2,3 β†’ 3. Level 2: only node 4 (left child of 2), so it is the rightmost by default.

Constraints

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

Think about it first

Hint 1 The visible node at each depth is the last node you would encounter scanning that level from left to right. So this is really "grab the last node of every level."
Hint 2 A breadth-first (level-order) traversal processes the tree one level at a time. If you know how many nodes are in the current level, the last one you dequeue is the rightmost.
Hint 3 Alternatively, do a DFS that visits the right child before the left, and record a node's value only the first time you reach a new depth β€” the first node seen at each depth from a right-first DFS is the rightmost one.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.