InterviewHubPRO
Section Overview
Q61

Question 61 of 100

Part 7: Binary Trees, BSTs & Traversals (53 - 64)

61%
DSA Patterns (Multi-Lang)•Part 7: Binary Trees, BSTs & Traversals (53 - 64)

Binary Tree Right Side View.

In Simple Words: BFS level-order traversal. For each level, append the last element in that level to the result array. (Or reverse preorder DFS visit root -> right -> left tracking depth).

  • Time: $O(N)$ | Space: $O(W) = O(N)$
Multi-Language Solutions
Switch tabs or choose All
from collections import deque

def rightSideView(root: TreeNode | None) -> list[int]:
    if not root: return []
    res = []
    q = deque([root])
    while q:
        level_len = len(q)
        for i in range(level_len):
            node = q.popleft()
            if i == level_len - 1:
                res.append(node.val)
            if node.left: q.append(node.left)
            if node.right: q.append(node.right)
    return res