MediumLinked ListDoubly-Linked ListDepth-First Search

Flatten a Multilevel Doubly Linked List

1 approach, code in every language

Problem description

You are given a doubly linked list in which each node has the usual previous and next pointers, but may also carry a child pointer that leads to a separate doubly linked list. That child list can itself contain nodes with their own children, producing an arbitrarily deep multilevel structure.

Flatten the whole structure into a single-level doubly linked list. When a node has a child, its child list should be spliced in immediately after that node and before whatever originally followed it, mirroring a depth-first traversal. After flattening, every node's child pointer must be null, and the prev and next pointers must correctly describe the single-level list. Return the head of the flattened list.

Example 1

Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]

Output: [1,2,3,7,8,11,12,9,10,4,5,6]

The child list hanging off node 3 is inserted right after it, and that list's own child off node 8 is inserted after 8, all before the traversal returns to node 4.

Example 2

Input: head = [1,2,null,3]

Output: [1,3,2]

Node 1 has a child list starting at 3, so 3 is spliced between 1 and 2, and the child pointer is cleared.

Constraints

  • The number of nodes is in the range [0, 1000].
  • 1 <= Node.val <= 10^5

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free