A disaster-alert broadcast network is laid out as a binary relay tree. The root tower transmits to up to two next-hop towers -- a first-slot tower and a second-slot tower -- each of which may itself transmit onward to up to two further towers, and so on. A terminal tower is one with no next hops of its own. For every terminal tower in the network, report the full chain of tower IDs from the root down to it, written as the IDs in visit order joined by -> (for example 1->2->5). Report the chains in the order their terminal towers are reached by visiting, at every tower, the first-slot next hop (and everything beneath it) before the second-slot next hop.
The first line contains a single integer n, the number of tokens describing the network.
The second line contains n space-separated tokens in breadth-first (level) order: each token is either an integer tower ID or the literal word null marking a missing next hop. As is standard for this encoding, a tower that is itself null contributes no tokens for its own next hops. The root tower (the first token) is never null.
Print one line per terminal tower: the chain of tower IDs from the root to that terminal tower, joined by ->, in the visit order described above.
Example 1
Input
3 1 2 3
Expected
1->2 1->3
Explanation
The network is tower 1 transmitting to towers 2 and 3, both of which are terminal (no further next hops). Visiting the first slot before the second gives the chain '1->2' first, then '1->3'.
Example 2
Input
5 1 2 3 null 5
Expected
1->2->5 1->3
Explanation
Tower 1 transmits to towers 2 (first slot) and 3 (second slot). Tower 2 has no first-slot next hop but does have a second-slot next hop, tower 5. Tower 3 and tower 5 are both terminal. Visiting tower 2's subtree (including its second-slot tower 5) before tower 3 gives the chain '1->2->5' first, then '1->3'.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →