AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Binary Tree Right Side View

The key idea

From the right side you see exactly one node per level: the last node on that level. So the answer is the rightmost node at each depth. Walk the tree level by level (or depth by depth) and keep the last value you reach on each level.

Problem

Given the root of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom. From any given level you can only see the node that is furthest to the right, because the nodes in front of it block your view.

Constraints

Examples

Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]
Input: root = [1,null,3] Output: [1,3]
Input: root = [] Output: []

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems