Binary Tree Right Side View
mediumTrees+20 XPTime limit 2s
Imagine standing on the right side of the tree. Print the values you can see, from top to bottom — that is, the last node of every level.
Tree format. A binary tree is given on one line in level order (top to bottom, left to right), with null for a missing child — the same way most interview platforms show trees. Trailing nulls are left out, and an empty tree is the single word null. Example: 3 9 20 null null 15 7 is
3
/ \
9 20
/ \
15 7
Input: one tree.
Output: the visible values on one line, or empty for an empty tree.
Constraints: 0 ≤ nodes ≤ 10⁴. The tree has at most 10⁴ nodes and its height is at most 500, so recursion is safe in every language.
Watch out: the rightmost node of a level is not always a right child — 1 2 3 4 shows 4, which hangs on the left.
Sample input 1
1 2 3 null 5 null 4
Sample output 1
1 3 4
Sample input 2
1 null 3
Sample output 2
1 3
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).