Early Access: 87 spots left.

Claim
Coding Interview PatternsTree Breadth First SearchBinary Tree Right Side View

Problems

Binary Tree Right Side View

Medium·Tagstreebfsqueuedfs

Problem Statement

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. Note: Assume a standard `TreeNode` class is already provided in the execution environment, containing `val`, `left`, and `right` properties.

Examples

Example 1
Input
root: [1, 2, 3, null, 5, null, 4]
Tree
25134
Output
"[1, 3, 4]"
Why
Level 0: 1 is the only node. Level 1: 2 and 3 are present, 3 is the rightmost. Level 2: 5 and 4 are present, 4 is the rightmost.
Example 2
Input
root: [1, null, 3]
Tree
13
Output
"[1, 3]"
Why
Level 0: 1. Level 1: 3.
Example 3
Input
root: []
Output
"[]"
Why
The tree is empty.

Constraints

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

Hints

Stuck? Reveal a nudge toward the right pattern, one step at a time.

Hint 1
You can use a standard Level Order Traversal (BFS) to visit the nodes level by level.
Hint 2
If you process the nodes of a level from left to right, which node represents the 'right side view' for that level?
Hint 3
It's the very last node processed in the current level's inner loop! If your inner loop runs `i` from `0` to `levelSize - 1`, check if `i == levelSize - 1` and append that node's value to your result.