Problem 430 · LeetCode 430(opens in a new tab)
Flatten a Multilevel Doubly Linked List
MediumDepth-first search
Each node of a doubly linked list has next and prev pointers and also a child pointer. A child pointer may lead to another doubly linked list of the same kind, whose nodes may have children too, so the lists form several levels.
Rewrite the links so every node sits in one flat doubly linked list. A node's child list goes right after that node and before the node's old next. Set every child to null and return the head.
Example 1
Input: head = [1,2,3,4,null,null,5,6,null,7] Output: [1,2,5,7,6,3,4] Why: 5 → 6 hangs from 2, and 7 hangs from 5
2 more examples and the constraints
Example 2
Input: head = [4,8,null,9] Output: [4,9,8] Why: 9 is the child of 4, so it goes before 8
Example 3
Input: head = [] Output: [] Why: there is nothing to flatten
Constraints
- 0 ≤ number of nodes ≤ 1,000
- 1 ≤ Node.val ≤ 100,000
- The input array lists each level in turn; leading nulls mark which node above it hangs from
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collect in order, then relinkO(n)
- Splice child lists in placeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 1,000 nodes | Verdict |
|---|---|---|---|
| Collect, then relink | O(n) | Simple; stores every node | |
| Splice in place | O(n) | Best; constant memory |
n = number of nodes across all levels.
Edge cases to test
- Empty list. head is null; return null.
- No children. The list is already flat and comes back unchanged.
- Child on the last node. There is no old next, so the child list's tail keeps
next = null; skip setting a prev on null. - Deep nesting. A chain of 1,000 levels; the in-place walk needs no recursion, so there is no stack depth problem.
Common mistakes
- Forgetting to set
child.prev = nodeornode.next.prev = tail, which leaves the list correct forwards only. - Leaving
node.childset; the result must have every child pointer null. - Pushing the child before the next on the stack, which puts the rest of the level before the child list.
How to talk through it
- 1Clarify. Does the child list go right after its parent? Must child pointers be cleared? Can the head be null?
- 2Name the order. It is a depth-first walk: a node, then its child list, then its next.
- 3Simple version. Record the nodes in that order with a stack, then relink them: O(n) time and memory.
- 4In place. At a node with a child, find the child list's tail and splice the whole list between the node and its next.
- 5Test out loud. Try an empty list, a child on the last node, and two levels of nesting.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?