
Sponsored
Sponsored
In this approach, we utilize a stack to achieve depth-first traversal of the multilevel doubly linked list. We push nodes into the stack starting from the head, along with managing the child nodes as higher priority over next nodes. This ensures that we process all child nodes before moving on to the next nodes.
Time Complexity: O(n) where n is the number of nodes. Each node is visited once.
Space Complexity: O(n) for the stack in the worst case scenario.
1#include <stack>
2
3class Solution {
4public:
5 Node* flatten(Node* head) {
6 if (!head) return head;
7 std::stack<Node*> stk;
8 Node* curr = head;
9
10 while (curr) {
11 if (curr->child) {
12 if (curr->next) stk.push(curr->next);
13 curr->next = curr->child;
14 curr->next->prev = curr;
15 curr->child = nullptr;
16 }
17
18 if (!curr->next && !stk.empty()) {
19 curr->next = stk.top();
20 stk.pop();
21 if (curr->next) curr->next->prev = curr;
22 }
23 curr = curr->next;
24 }
25
26 return head;
27 }
28};The C++ implementation also uses a stack but features cleaner syntax through the usage of standard stack data structure. The algorithm moves through the list, reassigning next pointers to child nodes, and then uses the stack to remember where to return once a child list ends.
This approach utilizes recursion to handle the traversing and flattening of lists. By inherently using the function call stack, it efficiently manages shifts between the parent and child lists, automatically flattening the entire structure as it recursively resolves each node and its children.
Time Complexity: O(n) due to the necessity to visit each node once.
Space Complexity: O(d) where d is the maximum depth of the children, necessitating stack space for recursion.
The recursive C solution uses a helper function inside the primary function to handle recursive flattening, where each call processes and flattens the child list before linking back to the parent node’s next list.