Stand on the right side of a binary tree and look at it. At each level you see only the rightmost node. Print the values you see, from the top level down.
Constraints
- 1 ≤ number of nodes ≤ 10000
- the root is not null
Input and output
- Input
- Line 1: n, the number of tokens. Line 2: the tree in level order — n tokens, each an integer or `null` for a missing child (trailing nulls may be left out).
- Output
- The visible values, top to bottom, space-separated.
Examples
Input 1
7
1 2 3 null 5 null 4Output
1 3 4Level 1 shows 1, level 2 shows 3, level 3 shows 4 (5 is hidden behind it).
Input 2
4
1 2 null 3Output
1 2 3Every level has one node on the left side, and all are visible: 1 2 3.
Show hints
- Visit the tree level by level.
- The last node you pop on each level is the one you can see.
Show the explanation
Do a breadth-first traversal one level at a time: note the queue size at the start of a level, pop exactly that many nodes, and record the last one. That node is the rightmost of its level even if it is a left child (as with 4 in the first sample, where the right side of level 3 is empty). A DFS that visits right before left and records the first node at each new depth works too.
Original UniCircle question. Last reviewed 22 Oct 2026.
