Flatten a Multilevel Linked List
Problem Description
You are given a linked list where each node has three fields: `val`, `next` (pointer to the next node), and `child` (pointer to the head of a sub-list). The `child` pointer may or may not be `null`. Sub-lists can themselves have child pointers — creating multiple levels of nesting.
Flatten the list into a single-level doubly linked list in **depth-first order**: whenever a node has a child, the child list is fully inserted between that node and its `next` node, before continuing with the parent list.
Return the head of the flattened list.
**Example 1:**
```
Input:
Level 1: 1 <-> 2 <-> 3 <-> 4
|
Level 2: 5 <-> 6
|
Level 3: 7
Output: 1 <-> 2 <-> 5 <-> 7 <-> 6 <-> 3 <-> 4
```
**Example 2:**
```
Input:
Level 1: 10 <-> 20 <-> 30
|
Level 2: 40 <-> 50
Output: 10 <-> 40 <-> 50 <-> 20 <-> 30
```
Constraints
- The number of nodes in total (across all levels) is in the range [0, 1000].
- Node values are in the range [1, 10^5].
- The depth of nesting is at most 1000.
- The flattened list must be a valid doubly linked list (prev and next pointers both correct).
Follow-up
Solve this recursively in O(n) time. How does the call-stack depth compare to the iterative approach's explicit stack depth?
Hints
Try the problem first. If you get stuck, you can reveal hints one at a time.
Solution
Leaderboard
No entries yet for python.
Be the first — submit an accepted solution.