Any one can help me with the Explore LinkedList question??pls

This question ask me to Flatten a Multilevel Doubly Linked List(in conclusion chapter):

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.

And my code get TLE solution, can anyone help me with that, I think the complexity is already O(n).

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, prev, next, child):
        self.val = val
        self.prev = prev
        self.next = next
        self.child = child
"""
class Solution(object):
    def flatten(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if not head:
            return head
        def helper(node):
            new = Node(0, None, node, None)
            curr = new
            while node:
                curr = node
                if node.child:
                    start, end = helper(node.child)
                    node = node.next
                    curr.next = start
                    start.prev = curr
                    curr.child = None
                    end.next = node
                    if node:
                        node.prev = end
                    curr = end
                else:
                    node = node.next
            return new.next, curr
        return helper(head)[0]

Thanks in advanced!

Comments (0)