MediumLinked ListDoubly-Linked ListDepth-First Search

Flatten a Multilevel Doubly Linked List

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now