/*// Definition for a Node.class Node { public int val; public Node prev; public Node next; public Node child;};*/classSolution{publicNodeflatten(Nodehead){if(head==null){returnnull;}Nodedummy=newNode();dummy.next=head;preorder(dummy,head);dummy.next.prev=null;returndummy.next;}privateNodepreorder(Nodepre,Nodecur){if(cur==null){returnpre;}cur.prev=pre;pre.next=cur;Nodet=cur.next;Nodetail=preorder(cur,cur.child);cur.child=null;returnpreorder(tail,t);}}
/*// Definition for a Node.class Node {public: int val; Node* prev; Node* next; Node* child;};*/classSolution{public:Node*flatten(Node*head){flattenGetTail(head);returnhead;}Node*flattenGetTail(Node*head){Node*cur=head;Node*tail=nullptr;while(cur){Node*next=cur->next;if(cur->child){Node*child=cur->child;Node*childTail=flattenGetTail(cur->child);cur->child=nullptr;cur->next=child;child->prev=cur;childTail->next=next;if(next)next->prev=childTail;tail=childTail;}else{tail=cur;}cur=next;}returntail;}};