Python | Leetcode Python题解之第430题扁平化多级双向链表
题目:
题解:
class Solution:def flatten(self, head: "Node") -> "Node":def dfs(node: "Node") -> "Node":cur = node# 记录链表的最后一个节点last = Nonewhile cur:nxt = cur.next# 如果有子节点,那么首先处理子节点if cur.child:child_last = dfs(cur.child)nxt = cur.next# 将 node 与 child 相连cur.next = cur.childcur.child.prev = cur# 如果 nxt 不为空,就将 last 与 nxt 相连if nxt:child_last.next = nxtnxt.prev = child_last# 将 child 置为空cur.child = Nonelast = child_lastelse:last = curcur = nxtreturn lastdfs(head)return head