 All Problems
Flatten a Multilevel Doubly Linked List
medium
linked list
depth-first search
doubly-linked list
amazon
facebook
google

You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have their own child lists, and so on to produce a multilevel data structure.

Given the head of the first level of the list, flatten the list so that all nodes appear in a single-level doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.

For this problem, represent the input as: each line is one level of nodes; "null" separates where a child pointer branches off.

Example:

Input:
1 2 3 4 5 6
7 8 9 10
11 12
Connections: node 3 child→7, node 8 child→11
Output: 1 2 3 7 8 11 12 9 10 4 5 6

Since this structure is complex to encode textually, we simplify input: provide a pre-order DFS traversal of what the flattened list should look like, and you implement the algorithm for the sample.

Input format: Three lines representing the three sub-lists: main, first child chain, second child chain.

Output format: Flattened list.

Run to check your code against the sample cases, or submit to run every case