430. Flatten a Multilevel Doubly Linked List

1. Description

You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. 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.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

2. Example

Example 1:
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 as follows:
Example 1
After flattening the multilevel linked list it becomes:
Example 1

Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]

3. Constraints

  • The number of Nodes will not exceed 1000.
  • 1 <= Node.val <= $10^5$

4. Solutions

My Accepted Solution

n is the number of nodes in m_head
Time complexity: O(n)
Space complexity: O(n)

// Depth-first Search && Recursion
// Also, if we could use recursion, we could use iteration with a stack.
class Solution {
private:
    Node* guardHead;
    Node* iter;

public:
    Node* flatten(Node* m_head) {
        guardHead = new Node();
        iter = guardHead;

        iterate(m_head);

        if (guardHead->next) {
            guardHead->next->prev = nullptr;
        }

        for (iter = guardHead->next; iter; iter = iter->next) {
            iter->child = nullptr;
        }

        return guardHead->next;
    }

    void iterate(Node* m_head) {
        if (m_head) {
            iter->next = m_head;
            m_head->prev = iter;
            iter = m_head;

            auto originNextNode = m_head->next;
            iterate(m_head->child);
            iterate(originNextNode);
        }
    }
};
comments powered by Disqus