You are given the root of a binary tree. Picture yourself to the right of the tree, looking at it from the side. On each level you see only the node that is furthest right; everything else on that level is hidden behind it.
Return the values you see, from the top level down. An empty tree gives an empty list.
Example 1
Input: root = [6, 2, 8, null, 4, null, null, 3] Output: [6, 8, 4, 3] Why: levels 2 and 3 have nothing to their right
2 more examples and the constraints
Example 2
Input: root = [3, 9, 7, 5, 1] Output: [3, 7, 1] Why: the last node of each level
Example 3
Input: root = [] Output: [] Why: no tree, nothing to see
Constraints
- 0 ≤ number of nodes ≤ 100
- −100 ≤ node value ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Level order, keep the lastO(n)
- DFS, right side firstO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 nodes | Verdict |
|---|---|---|---|
| Level order, keep the last | O(n) | Passes; easy to explain | |
| DFS, right side first | O(n) | Best; less memory, less code |
n = number of nodes, h = height of the tree, w = width of the widest level.
Edge cases to test
- Empty tree.
root = []must give[], not an error. - A left node can show. In Example 1, 4 and 3 are left of the root but nothing is to their right on their levels.
- One long chain. [1, 2, null, 3] has one node per level, so every node is seen.
- Equal values. The answer holds values, so repeated values simply repeat.
Common mistakes
- Following only right children, which misses deeper levels that exist only on the left.
- In the DFS, visiting the left child first, which records the leftmost node instead.
- In the BFS, reading the queue size inside the loop while children are being added.
How to talk through it
- 1Clarify. One value per level, top to bottom? What do I return for an empty tree?
- 2Point out the trap. It is not just the right edge: a left node is seen when its level has nothing further right.
- 3Give the BFS. Level by level, keep the last node of each level. O(n) time, O(w) space.
- 4Code the DFS. Right before left, record a node when depth equals the list length. Say why that test works.
- 5Test out loud. Run Example 1, where 4 and 3 are seen, and the empty tree.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?