/* Leet Code 430. Flatten a Multilevel Doubly Linked List You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. Example 1: if (curr->child) { if (curr->next) stk.push(curr-next); curr->next = curr->child; curr->child->prev = curr; curr->child = nullptr; } _________ _________ _________ _________ _________ _________ |prev next|---->|prev next|---->|prev next|---->|prev next|---->|prev next|---->|prev next| | 1 |<----| 2 |<----| 3 |<----| 4 |<----| 5 |<----| 6 | | child | | child | | child | | child | | child | | child | |_________| |_________| |_________| |_________| |_________| |_________| | | ____v____ _________ _________ _________ |prev next|---->|prev next|---->|prev next|---->|prev next| | 7 |<----| 8 |<----| 9 |<----| 10 | | child | | child | | child | | child | |_________| |_________| |_________| |_________| | | ____v____ _________ |prev next|---->|prev next| | 11 |<----| 12 | | child | | child | |_________| |_________| if (curr->next == nullptr && !stk.empty()) { // pop stack Node* node = stk.top(); curr->next = node; node->prev = curr; stk.pop(); } 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] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ |p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|--|p n|-->|p n| | 1 |<--| 2 |<--| 3 |<--| 7 |<--| 8 |<--| 11|<--| 12|<--| 9 |<--| 10|<--| 4 |<-| 5 |<--| 6 | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- Constraints: * The number of Nodes will not exceed 1000. * 1 <= Node.val <= 10^5 How the multilevel linked list is represented in test cases: We use the multilevel linked list from Example 1 above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: [1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null] Merging the serialization of each level and removing trailing nulls we obtain: [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Recursive DFS (Cleanest, Bloomberg loves recursion + linked lists) Idea: Treat it like a tree preorder traversal. For each node: * Recurse on its child first (flatten the entire subtree). * Then attach the original next after the flattened child. * Set child = nullptr. C++ Code (Recursive - O(n) time, O(n) stack space): */ #include #include using namespace std; class Node { public: Node(int i) : val(i), prev(nullptr), next(nullptr), child(nullptr) {} int val; Node* prev; Node* next; Node* child; }; #define CLASS_NAME(name) #name class SolutionStack { public: Node* flatten(Node* head) { if (head == nullptr) return nullptr; Node* curr = head; stack stk; while (curr != nullptr) { if (curr->child) { // process child, save next if (curr->next) stk.push(curr->next); curr->next = curr->child; curr->child->prev = curr; curr->child = nullptr; } // If we finish traversing child, flatten parent if (curr->next == nullptr && !stk.empty()) { Node* node = stk.top(); curr->next = node; node->prev = curr; stk.pop(); } curr = curr->next; } return head; } string name() { return CLASS_NAME(SolutionStack); } }; class SolutionRecursiveDFS { public: Node* flatten(Node* head) { if (!head) return nullptr; // Helper returns the tail of the flattened list starting from curr function dfs = [&](Node* curr, Node* rest) -> Node* { if (!curr) return rest; // Flatten child first, then original next becomes the new "rest" curr->next = dfs(curr->child, dfs(curr->next, rest)); if (curr->next) { curr->next->prev = curr; } curr->child = nullptr; // Important: clear child return curr; }; dfs(head, nullptr); return head; } string name() { return CLASS_NAME(SolutionRecursiveDFS); } }; class SolutionRecursiveTailFinding { public: Node* flatten(Node* head) { if (!head) return nullptr; // Helper function that returns the tail of the flattened subtree auto dfs = [&](auto&& self, Node* node) -> Node* { Node* curr = node; Node* tail = node; // track the last node in this flattened segment while (curr) { cout << "curr: " << curr->val << endl; // Save curr->next Node* saved_next = curr->next; if (curr->child) { cout << " recurse\n"; // getting here means at node with child Node* childTail = self(self, curr->child); //***************************************************** // getting here means we returned from processing child // segment. childTail will be returned. //***************************************************** cout << " saved_next: " << (saved_next != nullptr ? to_string(saved_next->val) : "nullptr") << endl; cout << " curr: " << curr->val << endl; cout << " curr->child: " << curr->child->val << endl; cout << " childTail: " << childTail->val << endl; // Connect child list after current node. // curr will be parent of child segment being processed (curr->child) curr->next = curr->child; curr->child->prev = curr; // Connect saved next after child tail childTail->next = saved_next; if (saved_next) saved_next->prev = childTail; // Clear child pointer curr->child = nullptr; // Update tail to end of child segment tail = childTail; } else { tail = curr; } curr = saved_next; } return tail; }; dfs(dfs, head); return head; } string name() { return CLASS_NAME(SolutionRecursiveTailFinding); } }; class SolutionIterativeTailFinding { public: Node* flatten(Node* head) { if (!head) return nullptr; for (Node* curr = head; curr; curr = curr->next) { if (curr->child) { Node* nextSaved = curr->next; // Save sibling // Attach child curr->next = curr->child; curr->child->prev = curr; curr->child = nullptr; // Clear child // Find tail of the child subtree Node* tail = curr->next; while (tail->next) { tail = tail->next; } // Attach saved next after tail tail->next = nextSaved; if (nextSaved) { nextSaved->prev = tail; } } } return head; } string name() { return CLASS_NAME(SolutionIterativeTailFinding); } }; /* Solution with pointers We traverse the list with a single pointer curr. Whenever we find a node with a child, we: * Find the tail of the child list (by walking to the end). * Weave the child list right after the current node. * Connect the original next after the child tail. * Set child = nullptr. Continue from the original next (now after the inserted child list). _____ _____ _____ _____ _____ _____ |p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n| | 1 |<--| 2 |<--| 3 |<--| 4 |<--| 5 |<--| 6 | | c | | c | | c | | c | | c | | c | ----- ----- ----- ----- ----- ----- | __v__ _____ _____ _____ |p n|-->|p n|-->|p n|-->|p n| | 7 |<--| 8 |<--| 9 |<--| 10| | c | | c | | c | | c | ----- ----- ----- ----- | __v__ _____ |p n|-->|p n| | 11|<--| 12| | c | | c | ----- ----- >>>>>>>>>>>>>>>>>>>>>>>>>> step 1 _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ |p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n| | 1 |<--| 2 |<--| 3 |<--| 7 |<--| 8 |<--| 9 |<--| 10|<--| 4 |<--| 5 |<--| 6 | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- | __v__ _____ |p n|-->|p n| | 11|<--| 12| | c | | c | ----- ----- >>>>>>>>>>>>>>>>>>>>>>>>>> step 2 _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ |p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|-->|p n|--|p n|-->|p n| | 1 |<--| 2 |<--| 3 |<--| 7 |<--| 8 |<--| 11|<--| 12|<--| 9 |<--| 10|<--| 4 |<-| 5 |<--| 6 | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | | c | ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- */ class SolutionPointers { public: void printList(Node* node) { while (node != nullptr) { cout << node->val << " "; node = node->next; } cout << endl; }; Node* flatten(Node* head) { Node* curr = head; printList(head); while (curr) { if (curr->child) { // Step 1: Find the tail of the child subtree (O(depth) but overall O(n)) Node* childTail = curr->child; while (childTail->next != nullptr) { childTail = childTail->next; } // Step 2: Save the original next node Node* nextTemp = curr->next; // Step 3: Weave the child list right after curr curr->next = curr->child; curr->child->prev = curr; // Step 4: Connect childTail to the original next childTail->next = nextTemp; if (nextTemp != nullptr) { nextTemp->prev = childTail; } // Step 5: Clear the child pointer curr->child = nullptr; printList(curr); } // CRITICAL: Always move forward to the next node. // This ensures we process the newly inserted child nodes in the same pass. curr = curr->next; } return head; } string name() { return CLASS_NAME(SolutionPointers); } }; Node* createTestCase() { /* Test Case 1: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL */ Node * _1 = new Node( 1); Node * _2 = new Node( 2); _2->prev=_1; _1->next=_2; Node * _3 = new Node( 3); _3->prev=_2; _2->next=_3; Node * _4 = new Node( 4); _4->prev=_3; _3->next=_4; Node * _5 = new Node( 5); _5->prev=_4; _4->next=_5; Node * _6 = new Node( 6); _6->prev=_5; _5->next=_6; Node * _7 = new Node( 7); _3->child=_7; Node * _8 = new Node( 8); _8->prev =_7; _7->next=_8; Node * _9 = new Node( 9); _9->prev =_8; _8->next=_9; Node *_10 = new Node(10); _10->prev =_9; _9->next=_10; Node *_11 = new Node(11); _8->child=_11; Node *_12 = new Node(12); _12->prev =_11; _11->next=_12; return _1; } void printStructure() { cout << "1---2---3---4---5---6--NULL" << endl; cout << " |" << endl; cout << " 7---8---9---10--NULL" << endl; cout << " |" << endl; cout << " 11--12--NULL" << endl; } vector expected{1,2,3,7,8,11,12,9,10,4,5,6}; vector printList(Node* node) { vector nodeList; while (node != nullptr) { cout << node->val << " "; nodeList.push_back(node->val); node = node->next; } cout << endl; cout << setw(50) << setfill('-') << '-' << endl; return nodeList; }; template struct Runner { void run() { Solution s; cout << s.name() << endl; Node* head = createTestCase(); printStructure(); Node* result = s.flatten(head); vector nodeList = printList(result); EXPECT_EQ(nodeList, expected); } }; int main(void) { { Runner runner; runner.run(); } { Runner runner; runner.run(); } { Runner runner; runner.run(); } { Runner runner; runner.run(); } { Runner runner; runner.run(); } return 0; }