"""
# 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):
if head is None:
return head
dummy = Node(-1, None, None, None)
stack = []
stack.append(head)
cur = dummy
while(len(stack) != 0):
top = stack.pop()
cur.next = top
cur.child = None
top.prev = cur
if top.next:
stack.append(top.next)
if top.child:
stack.append(top.child)
top.child = None
cur = cur.next
dummy.next.prev = None # break the dummy link is critical
return dummy.next
'''
def flatten(self, head):
if head is None:
return head
dummy = Node(-1, None, None, None)
tail = self.helper(dummy, head)
dummy.next.prev = None # break the dummy link is critical
return dummy.next
def helper(self, cur, head):
if head is None:
return cur
# self
cur.next = Node(head.val, cur, None, None)
cur = cur.next
# left -- child
cur = self.helper(cur, head.child)
# right -- next
cur = self.helper(cur, head.next)
return cur