FrontendInterviews.dev

Loading problem…

97. Binary Tree Right Side View

Medium•
Acceptance: 94.12%
•
🔓3/3 Pro unlocks today

Given the root of a binary tree, return the right side view of the tree. The right side view shows the rightmost node at each level when viewed from the right side.

Requirements

1. Problem Understanding

  • For each level of the tree, return the rightmost node's value
  • If viewing from the right side, you see the rightmost node at each level
  • Return values in order from top to bottom

Example Usage

// Example tree:
//       1
//      / \
//     2   3
//      \   \
//       5   4

// Right side view: [1, 3, 4]
// Level 0: 1 (rightmost)
// Level 1: 3 (rightmost)
// Level 2: 4 (rightmost)

Key Concepts

  • Use BFS (Breadth-First Search) to traverse level by level
  • Track the rightmost node at each level
  • Can also use DFS with level tracking
  • Right side view = last node in each level when traversing left to right

Constraints

  • The number of nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100
  • Handle empty tree (return empty array)
  • Handle single node tree
  • Handle unbalanced trees