Binary Tree Right Side View
Medium· BFS· DFS
Problem
Imagine looking at a binary tree from its right side. Return the values you would see, from top to bottom, which is the rightmost node at each depth.
Examples
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
At depth 2 the rightmost node is 4, even though 5 sits in the left subtree.
Input: root = [1,null,3]
Output: [1,3]
Constraints
- • 0 <= number of nodes <= 100
- • -100 <= Node.val <= 100
Hints & approach
Hint 1
The visible node is not always in the right subtree; a deeper left branch can show through.
Hint 2
You want exactly one node per depth: the last one in that level.
Hint 3
BFS by level and take the last node, or DFS visiting right before left and record the first node seen at each new depth.
Approachtry the hints first
Do a level-order traversal and, for each level, append the value of the last node dequeued. Alternatively, DFS with the right child explored first, and whenever the current depth equals the result length, this is the first (rightmost) node at that depth, so append it. Both touch each node once.
Time O(n) · Space O(h)