AlgoMaster Logo

Flatten a Multilevel Doubly Linked List

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Depth-First Search (DFS)

Intuition:

The multilevel doubly linked list can be visualized as a tree structure where some nodes have children. The task is equivalent to performing a depth-first traversal and flattening the tree into a single-level doubly linked list.

The recursive approach involves:

  • Traversing each node,
  • Recursively flattening any child node, and
  • Splicing the flattened child list into the main list.

Steps:

  1. Start from the head of the list.
  2. Traverse the list. For each node, check if it has a child.
  3. If a child exists, recursively flatten the child list.
  4. Splice the child list between the current node and the rest of the main list.
  5. Move the pointer to the next node and repeat the process.

Code:

2. Iterative Using Stack

Intuition:

An iterative approach can be implemented using a stack to simulate the recursive flow. By using a stack, we can handle the nested and continuation structure of the list explicitly:

  • Traverse through the list
  • When encountering a node with a child, push the next node to a stack for later processing.
  • Splice the child node into the main list.

Steps:

  1. Use a stack to keep track of the remaining nodes after encountering a child.
  2. Iterate over the list.
  3. If a node has a child, push its next to the stack, splice the child into the list, and continue.
  4. After processing the child, continue with the node from the stack if available.

Code: