VOOZH about

URL: https://www.geeksforgeeks.org/dsa/flatten-a-multi-level-linked-list-set-2-depth-wise/

⇱ Flatten a multi-level linked list (Depth wise) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flatten a multi-level linked list (Depth wise)

Last Updated : 10 Dec, 2024

Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to flatten the list so that all the nodes appear in a single-level linked list. Flatten the list in a way that all nodes at the first level should come first, then nodes of the second level, and so on.

Examples:

Input:

👁 2_5


Output: 1->4->6->2->5->7->3->8
Explanation: The multilevel linked list is flattened as it has no child pointers.

We have discussed flattening of a multi-level linked list where nodes have two pointers down and next. In the previous post, we flattened the linked list level-wise. How to flatten a linked list when we always need to process the down pointer before next at every node.

[Expected Approach] Using Recursion - O(n) Time and O(n) Space

The approach is to recursively flatten a multi-level linked list by traversing each node and its child nodes. First, flatten the child list using recursion. Once the child list is flattened, proceed to the next node in the sequence. During traversal, maintain a reference to the previously visited node and link it to the current node. This process ensures all nodes, from different levels, are connected in a single linear list while preserving the depth-wise order.


Output
5 7 8 30 10 19 22 50 28 

[Alternate Approach] Using Stack - O(n) Time and O(n) Space

The approach is to traverse the multi-level linked list using a stack. Start by pushing the head node onto the stack. Then, while the stack is not empty,pop the top node and process it. For each node, push its next and down pointers (if they exist) onto the stack. During this process, link the current node to the previous node, maintaining the list in a flattened form. The traversal ensures that nodes from all levels are connected in a single-level linked list, preserving the depth-wise order.


Output
5 7 8 30 10 19 22 50 28 
Comment
Article Tags:
Article Tags: