A phone bank organizes emergency alerts through a calling tree: member 1 is the organizer and starts the relay, and every other member is reached by exactly one other member who calls them directly. When a member receives the alert, they call their own direct contacts one at a time, in a fixed order assigned to them in advance; before moving on to call their next direct contact, a member waits until that contact — and everyone that contact goes on to reach — has fully finished being notified. In other words, a member's contacts are always called out one full branch at a time, in their assigned order.
Given the calling tree, determine the exact order in which all n members receive the alert, starting with the organizer.
Print the n member numbers in the order they receive the alert, space-separated on a single line, starting with 1.
Example 1
Input
4 1 2 1 3 2 4
Expected
1 2 4 3
Explanation
Member 1's contacts, in order, are 2 then 3. Member 1 calls 2 first; member 2's only contact is 4, so 4 is reached next, finishing that whole branch. Only then does member 1 move on to call member 3. The order is 1 2 4 3.
Example 2
Input
4 1 2 1 3 1 4
Expected
1 2 3 4
Explanation
Member 1 calls contacts 2, 3, and 4 in that order; none of them has any contacts of their own, so each branch finishes the instant it's reached, before the next call is placed. The order is 1 2 3 4.
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 →