思路:用dfs实现扁平化当前节点的child,并返回扁平化的最后一个节点childLast。如果next不为空,则将next链接在childLast后面。
代码:
class Solution {
public Node flatten(Node head) {
dfs(head);
return head;
}
public Node dfs(Node head){
Node cur = head;
Node last = null;
while (cur != null){
Node next = cur.next;
if(cur.child != null){
Node childLast = dfs(cur.child);
next = cur.next;
cur.next = cur.child;
cur.child.prev = cur;
if(next != null){
childLast.next = next;
next.prev = childLast;
}
cur.child = null;
last = childLast;
}else {
last = cur;
}
cur = next;
}
return last;
}
}
复杂度分析:时间o(n),n为链表元素个数。空间为0(d),d为链表深度,最坏为o(nb),即前n-1个节点next均为null,只有child