← DSA
MEDIUM

Binary Tree Right Side View

PracticeNeetCode ↗LeetCode ↗

Given the root of a binary tree, return the values visible when looking at the tree from the right side, ordered from top to bottom.

Example

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

Key Pointers

Step-by-Step Analysis

  1. If root is None, return [].
  2. BFS level by level, same pattern as Level Order Traversal.
  3. At the end of processing each level, append the value of the last node dequeued in that level to result.
  4. Return result once the queue is empty.

Complexity

Time: O(n) — Space: O(n)

Code

from collections import deque

def rightSideView(root: TreeNode | None) -> list[int]:
    if not root:
        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

Code Explanation

How the solution above works, piece by piece.

  1. Breadth-first search level by level, exactly like Level Order Traversal.
  2. level_size = len(queue) fixes how many nodes belong to the current level.
  3. i == level_size - 1 is the last (rightmost) node of the level: record it.
  4. Children are queued left then right, so the last node popped in each level is the rightmost one.
  5. O(n) time, O(width) queue.

Visual Walkthrough

Running it on root = [1, 2, 3, null, 5, null, 4]:

Rightmost node of each level12354level 0 → last is 1level 1 → last is 3level 2 → last is 4
Looking from the right you see the last node of each level. The BFS visits every level left to right, and i == level_size - 1 picks that last node: [1, 3, 4]. Note 5 is hidden behind 4.
visible from the right

Video Explanation

NeetCode — Binary Tree Right Side View, LeetCode 199