Flatten a Multilevel Doubly Linked List

Problem Id: 430 Difficulty: Medium


Intuition

Solution


class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        node = head
        while node is not None:
            if node.child is not None:
                insert = self.flatten(node.child)
            else:
                node = node.next
                continue
            tmp = node.next
            node.next = insert
            insert.prev = node
            node.child = None

            while insert.next:
                insert = insert.next

            insert.next = tmp
            if tmp:
                tmp.prev = insert
            node = insert
        return head