https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
这题其实是非常直观的dfs题目,每次遇到child的时候,进入下一层dfs,这个dfs需要返回两个点,一个是child list的头,另一个是child list的尾。此时遍历到的这个节点的next就会成为child list的头,child list的尾的next就需要和原来节点的next进行连接。然后我们从child list的尾部开始继续遍历。看代码即可,没什么很复杂的东西:
public Node flatten(Node head) {
return dfsFlatten(head)[0];
}
public Node[] dfsFlatten(Node head) {
if (head == null) return new Node[]{null, null};
Node current = head, tail = current;
while (current != null) {
tail = current;
if (current.child != null) {
Node next = current.next;
Node[] nextLvl = dfsFlatten(current.child);
current.next = nextLvl[0];
nextLvl[0].prev = current;
current.child = null;
current = nextLvl[1];
if (next != null) {
current.next = next;
next.prev = current;
}
} else {
current = current.next;
}
}
return new Node[]{head, tail};
}