DSAPrep
MediumTrees

Binary Tree Right Side View

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.

Example 1

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

Example 2

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

Example 3

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

Example 4

Input: root = []
Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
View original on LeetCode β†—

Standing to the right of the tree, the visible node at each depth is whichever node is rightmost at that depth. That can be found with BFS (take the last node of each level) or with a right-first DFS (the first node to reach a given depth wins, since right children are explored before left ones).

BFS (last node per level)

Time O(n)Space O(n)

Level-order traverse the tree; at each level, the last node processed is the rightmost one, and therefore the one visible from the right.

from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def rightSideView(self, root: TreeNode | None) -> list[int]:
if root is None:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
if i == level_size - 1:
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result

Complexity: every node is enqueued and dequeued once β†’ O(n) time. The queue can hold up to ~n/2 nodes at the widest level β†’ O(n) space.

DFS (right child first)

OptimalTime O(n)Space O(h)

Visit right children before left children, and record a node’s value the first time its depth is reached. Since right is explored first, the first node seen at each depth is guaranteed to be the rightmost one at that depth.

class Solution:
def rightSideView(self, root: TreeNode | None) -> list[int]:
result = []
def dfs(node: TreeNode | None, depth: int) -> None:
if node is None:
return
if depth == len(result):
result.append(node.val)
dfs(node.right, depth + 1)
dfs(node.left, depth + 1)
dfs(root, 0)
return result

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

1
2
3
5
4
1 / 4
seenresultdiscarded

depth 0 == len(result)=0, so record 1. Recurse right first.

Complexity: each node is visited exactly once β†’ O(n) time, identical to BFS. Recursion depth tracks tree height β†’ O(h) space, an improvement over BFS’s O(n) queue width on a wide, shallow tree.