Explain right-side view.
Skip to solutionKEEP THE
mediumDSA
How do you get the right-side view of a binary tree?
791 views
01
Understand the problem
treesbfs
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Do a level-order BFS and take the last node of each level, which is what you'd see from the right. Alternatively a DFS visiting right-first and recording the first node seen at each new depth. O(n).
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Level-order BFS, last per level
Run Playgroundfrom collections import deque
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def right_side_view(root):
if not root:
return []
view, q = [], deque([root])
while q:
n = len(q)
for i in range(n):
node = q.popleft()
if i == n - 1: # last node of this level
view.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
return view
# --- demo ---
root = TreeNode(1, TreeNode(2, None, TreeNode(5)), TreeNode(3, None, TreeNode(4)))
print(right_side_view(root)) # [1, 3, 4]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 48 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.