Flatten a Multilevel Doubly Linked List - Problem
You are given a doubly linked list that contains nodes with a next pointer, a prev pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, which also contains these special nodes. These child lists may have one or more children of their own, creating 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. The nodes in the child list should appear after the current node and before the current node's next node in the flattened list.
Return the head of the flattened list. All child pointers must be set to null.
Input & Output
Example 1 — Simple Multilevel
$
Input:
head = [1,2,3,null,null,7,8,null,null,null,null]
›
Output:
[1,2,7,8,3]
💡 Note:
Node 2 has child 7→8. After flattening: 1→2→7→8→3 with all child pointers set to null
Example 2 — Single Level
$
Input:
head = [1,2,3,4,5]
›
Output:
[1,2,3,4,5]
💡 Note:
No child nodes exist, so the list remains unchanged: 1→2→3→4→5
Example 3 — Empty List
$
Input:
head = null
›
Output:
null
💡 Note:
Empty list returns null
Constraints
- The number of Nodes will not exceed 1000
- 1 ≤ Node.val ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code