430. 扁平化多级双向链表
多级双向链表中,除了指向下一个节点和前一个节点指针之外,它还有一个子链表指针,可能指向单独的双向链表。这些子列表也可能会有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
给你位于列表第一级的头节点,请你扁平化列表,使所有结点出现在单级双链表中。
示例 1:
输入:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
输出:[1,2,3,7,8,11,12,9,10,4,5,6]
提示:
节点数目不超过 1000
1 <= Node.val <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明
方法一:迭代深度遍历,利用栈
/*
// Definition for a Node.
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
};
*/
class Solution {
public Node flatten(Node head) {
if(head==null)
{
return head;
}
Node dummy=new Node(0,null,head,null);
Node pre=dummy;
Node cur;
Deque<Node> res=new ArrayDeque<>();
res.push(head);
while(!res.isEmpty())
{
cur=res.pop();
pre.next=cur;
cur.prev=pre;
if(cur.next!=null)
{
res.push(cur.next);
}
if(cur.child!=null)
{
res.push(cur.child);
cur.child=null;
}
pre=cur;
}
dummy.next.prev=null;
return dummy.next;
}
}
方法二:递归DFS
class Solution {
public Node flatten(Node head) {
if(head==null)
{
return null;
}
Node dummy=new Node(0,null,head,null);
DFS(dummy,head);
dummy.next.prev=null;
return dummy.next;
}
public Node DFS(Node pre,Node cur)
{
if(cur==null)
{
return pre;
}
cur.prev=pre;
pre.next=cur;
Node temp=cur.next;
Node tail=DFS(cur,cur.child);
cur.child=null;
return DFS(tail,temp);
}
}