Given the
Output: [1,3,4]
Explanation: Level 0: 1 (rightmost = 1). Level 1: 2,3 (rightmost = 3). Level 2: 5,4 (rightmost = 4).
Output: [1,3]
Constraints:
0 <= Number of nodes <= 100 -100 <= Node.val <= 100
Contents
Solution — BFS Level Order Complexity Analysis
Perform a standard level-order BFS. For each level, the last node dequeued is the rightmost visible node — add its value to the result.
Algorithm:
- Enqueue the root.
- For each level, snapshot
levelSize = queue.size() . - Dequeue all
levelSize nodes, enqueue their children left-before-right. - After processing the level, the last dequeued node is the rightmost — record its value.
Trace through Example 1: root = [1,2,3,null,5,null,4]
| Level | Nodes processed | Rightmost |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 2, 3 | 3 |
| 2 | 5, 4 | 4 |
- Time: O(n) — every node is enqueued and dequeued exactly once.
- Space: O(n) — the queue holds at most n/2 nodes at the widest level.