题目
关键词
双向链表,递归
代码记录
递归解法
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
res_head,res_tail=self.flatten_child(head)
return res_head
def flatten_child(self,head):
res_head=head
cur=head
tail=None
while cur:
if cur.child:
child_head,child_tail=self.flatten_child(cur.child)
next_head,next_tail=self.flatten_child(cur.next)
cur.next=child_head
child_head.prev=cur
cur.child=None
child_tail.next=next_head
if next_head:
next_head.prev=child_tail
tail=next_tail
else:
tail=child_tail
return res_head,tail
else:
tail=cur
cur=cur.next
return res_head,tail