Skip to problem
←

Flatten a Multilevel Doubly Linked List

Medium 0 attempts

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.

Reconnect the original nodes without changing their values. Return the head node, with correct prev links and every child pointer set to null. An empty input returns null.

Function contract

head is a node with val, prev, next, and child pointers, or null. Test inputs use numbers or {val, child:[...]} entries; [] becomes null.

Output: Return the head of the flattened list using the original nodes and values. All child pointers must be null and prev links must be correct. The runner displays the returned list as a value array.

Example 1

Input
head = [1,{"val":2,"child":[3,{"val":4,"child":[5]}]},6]
Output
[1,2,3,4,5,6]

Example 2

Input
head = []
Output
[]
Visual Aid
Finish each child list before returning
Before126345↔↔↔childchildAfter1↔2↔3↔4↔5↔6

Visit 3, 4, and nested child 5 before returning to 6. Reconnect both directions and clear every child pointer.

Constraints
  • 0 <= number of nodes <= 1000
  • 1 <= Node.val <= 10^5
Topics

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.

javascript
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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript