Binary Tree Right Side View - 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.

When you stand on the right side, you can only see the rightmost node at each level of the tree.

Example: For a tree with root [3,9,20,null,null,15,7], you would see nodes with values [3,20,7] - one from each level, taking the rightmost visible node.

Input & Output

Example 1 — Standard Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [3,20,7]
💡 Note: Level 0: only node 3 is visible. Level 1: nodes 9 and 20, but only 20 is rightmost. Level 2: nodes 15 and 7, but only 7 is rightmost.
Example 2 — Right-Skewed Tree
$ Input: root = [1,null,3]
Output: [1,3]
💡 Note: Level 0: node 1 is visible. Level 1: only node 3 exists and is rightmost.
Example 3 — Single Node
$ Input: root = [1]
Output: [1]
💡 Note: Only one node exists, so it's the only node visible from the right side.

Constraints

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

Visualization

Tap to expand
Binary Tree Right Side View INPUT Binary Tree Structure 3 9 20 15 7 L0 L1 L2 Input Array Representation: [3, 9, 20, null, null, 15, 7] Rightmost (visible) Hidden nodes ALGORITHM (BFS) 1 Initialize Queue Start with root node [3] 2 Process Each Level Track level size, iterate 3 Capture Rightmost Last node of each level 4 Build Result Collect all rightmost values BFS Level-by-Level: 3 --> 3 9 20 --> 20 15 7 --> 7 Queue contents Rightmost FINAL RESULT Right Side View: Level 0 3 Level 1 20 Level 2 7 Output Array: [3, 20, 7] OK - 3 nodes visible from right side Key Insight: BFS naturally processes nodes level by level. By tracking the size of each level, we can identify the last node processed in each level - this is the rightmost node visible from the right side. Time Complexity: O(n) | Space Complexity: O(w) where w is maximum width of the tree. TutorialsPoint - Binary Tree Right Side View | BFS Approach
Asked in
Facebook 45 Amazon 38 Microsoft 25
338.0K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen