Binary Tree Right Side View
The right view needs exactly one node per depth: the first one DFS reaches when it always visits the right child before the left. A node fills a depth only the first time DFS arrives there — any later arrival at the same depth (from a shorter right branch or a deeper left branch) is invisible from the right.
Details
Animated on: Given the root of a binary tree, return the values of the nodes visible from the right side, ordered from top to bottom.
Problem:Binary Tree Right Side ViewMedium
Pattern:Tree BFS and Level Order
Binary Trees
step 1 / 17
Call rightSideView(1). result starts empty; DFS explores right children before left so the first node to reach each new depth is always the rightmost one.
1FUNCTION rightSideView(root):2 result <- []3 DFS(root, 0, result)4 RETURN result5FUNCTION DFS(node, depth, result):6 IF node = null: RETURN7 IF depth = LENGTH(result):8 APPEND node.val TO result9 DFS(node.right, depth + 1, result)10 DFS(node.left, depth + 1, result)
← / → step · space play · Home restart
Every step in words
Show all 17 steps
- Call rightSideView(1). result starts empty; DFS explores right children before left so the first node to reach each new depth is always the rightmost one.
- Enter DFS(1, depth=0). Call stack: DFS(1, depth=0).
- depth (0) equals result.length (0) — first arrival at this level, so 1 is the rightmost node seen so far. result = [1].
- Enter DFS(3, depth=1). Call stack: DFS(1, depth=0) -> DFS(3, depth=1).
- depth (1) equals result.length (1) — first arrival at this level, so 3 is the rightmost node seen so far. result = [1, 3].
- Enter DFS(5, depth=2). Call stack: DFS(1, depth=0) -> DFS(3, depth=1) -> DFS(5, depth=2).
- depth (2) equals result.length (2) — first arrival at this level, so 5 is the rightmost node seen so far. result = [1, 3, 5].
- 5 has no children — both recursive calls hit the null base case immediately, so DFS(5, depth=2) returns and pops.
- Both subtrees of 3 are done. DFS(3, depth=1) returns and pops. result so far: [1, 3, 5].
- Enter DFS(2, depth=1). Call stack: DFS(1, depth=0) -> DFS(2, depth=1).
- depth (1) != result.length (3) — a node further right already filled this level, so 2 stays hidden. result unchanged: [1, 3, 5].
- Enter DFS(4, depth=2). Call stack: DFS(1, depth=0) -> DFS(2, depth=1) -> DFS(4, depth=2).
- depth (2) != result.length (3) — a node further right already filled this level, so 4 stays hidden. result unchanged: [1, 3, 5].
- 4 has no children — both recursive calls hit the null base case immediately, so DFS(4, depth=2) returns and pops.
- Both subtrees of 2 are done. DFS(2, depth=1) returns and pops. result so far: [1, 3, 5].
- Both subtrees of 1 are done. DFS(1, depth=0) returns and pops. result so far: [1, 3, 5].
- DFS finished. result = [1, 3, 5] — the highlighted path shows the rightmost node at every depth.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.