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