Flatten a Multilevel Doubly Linked List
You're given a doubly linked list in which any node may additionally hold a child pointer to the head of its own separate doubly linked list, and those child lists can themselves contain further nested children, forming a multilevel structure. Collapse the entire structure into one single-level doubly linked list, inserting each child list depth-first between its parent node and the parent's original next node. Once flattened, no node should retain a child pointer.
Sample Input and Output
Example 1 ยท Run Sample
head = [1,{"val":2,"child":[3,{"val":4,"child":[5]}]},6] [1,2,3,4,5,6] Example 2
head = [] [] - 0 <= number of nodes <= 1000
- 1 <= Node.val <= 10^5
Test Cases (2)
Approach: Iterative with Stack
Traverse the list. When a node has a child, push its next onto a stack, then splice the child list in as the new next. When reaching a node with no next and the stack is non-empty, pop and continue from there.
function flattenAMultilevelDoublyLinkedList(head) {
if (!head) return null;
let curr = head;
const stack = [];
while (curr) {
if (curr.child) {
if (curr.next) stack.push(curr.next);
curr.next = curr.child;
curr.next.prev = curr;
curr.child = null;
}
if (!curr.next && stack.length) {
const next = stack.pop();
curr.next = next;
next.prev = curr;
}
curr = curr.next;
}
return head;
}Time Complexity: O(n)
Space Complexity: O(n) for the stack
Saved in this browser only. Private to you.