Visualize

Pattern visualizer

Right Side View of Binary Tree

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. 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..

Binary Trees

step 1 / 17
4
2
1
3
5
line 2

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.

Pseudocode
1FUNCTION rightSideView(root):
2 result <- []
3 DFS(root, 0, result)
4 RETURN result
5FUNCTION DFS(node, depth, result):
6 IF node = null: RETURN
7 IF depth = LENGTH(result):
8 APPEND node.val TO result
9 DFS(node.right, depth + 1, result)
10 DFS(node.left, depth + 1, result)

← / → step · space play · Home restart

Where to practice Binary Trees