Example 1
- Input
- root = [1,2,3,null,5,null,4]
- Output
- [1,3,4]
Depth 0 contains 1; depth 1 contains 2 then 3; depth 2 contains 5 then 4. Taking the rightmost value from each depth gives [1,3,4].
Given the root of a binary tree, return the values visible when looking from the right side, which is exactly the rightmost node of each level from top to bottom.
Given the root of a binary tree, imagine standing on its right side and return the values you can see from top to bottom.
Exactly one node per level is visible: the rightmost node at that depth, even when it sits in a left subtree.
[0, 100].-100 <= Node.val <= 100Depth 0 contains 1; depth 1 contains 2 then 3; depth 2 contains 5 then 4. Taking the rightmost value from each depth gives [1,3,4].
Each depth has only one node, so both 1 and 3 are visible.
There are no levels in an empty tree, so the view is an empty list.
Node 3 hides 2 at depth 1, but its subtree stops there. At depths 2 and 3, nodes 4 and 5 in the left subtree are the only existing nodes and remain visible.
Visibility depends on position, not distinct values. Each depth contributes a 7, so repeated values must stay in the answer.
The right side view chooses one node at each depth: the rightmost existing node, regardless of its value or whether its path follows right-child links. In Example 1, depth 2 contains 5 and 4, so 4 hides 5. Breadth-first search can take the last node of each left-to-right level; depth-first search can visit right children first and take the first node at each new depth. Both must still explore left subtrees, because those may extend below every node on the right.
Reveal Level Order Last Node: intuition, complexity, and code
A per-level view is a traversal plus a selection rule: left-to-right BFS takes the last node, while right-first DFS takes the first node at each depth. Visit all subtrees even when the current depth already has a selected value, because deeper levels may still need an answer.