Problem 725
Flatten a Multilevel Linked List
Medium · 20 pts · Linked List, Depth-First Search, Stack
Problem
Every node of a multilevel linked list has a value, a next pointer and a child pointer; a child points to the head of another list, which can have children of its own. Flatten it into a single list: every node's child list is placed right after that node, before the node's next node, recursively. Print the values in the flattened order. A stack (or recursion) does it: when a node has a child, remember its next node, walk into the child list, and come back afterwards.
Input
The first line contains N, the number of nodes (numbered 0 to N-1; node 0 is the head). Each of the next N lines contains VALUE, NEXT and CHILD for one node, where NEXT and CHILD are node numbers or -1.
Output
Print the node values in the flattened order, separated by spaces.
Constraints
1 <= N <= 1000; every node except the head is reachable from exactly one next or child pointer; there are no cycles
Example input
6 1 1 -1 2 2 3 3 -1 -1 7 4 5 8 -1 -1 11 -1 -1
Example output
1 2 7 11 8 3
Explanation
The head list is 1 → 2 → 3, node 2 has the child list 7 → 8, and 7 has the child 11. Flattening puts 7, 11, 8 between 2 and 3, giving 1 2 7 11 8 3.