Skip to content

Commit 8710946

Browse files
authored
Create Solution.java
1 parent 43cd3c3 commit 8710946

File tree

1 file changed

+32
-0
lines changed
  • solution/0430.Flatten a Multilevel Doubly Linked List

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public Node flatten(Node head) {
3+
if (head == null) {
4+
return null;
5+
}
6+
dfs(head);
7+
head.prev = null;
8+
return head;
9+
}
10+
11+
private Node dfs(Node head) {
12+
Node cur = head;
13+
while (cur != null) {
14+
head.prev = cur;
15+
Node next = cur.next;
16+
if (cur.child != null) {
17+
Node h = dfs(cur.child);
18+
cur.child = null;
19+
Node t = h.prev;
20+
cur.next = h;
21+
h.prev = cur;
22+
t.next = next;
23+
if (next != null) {
24+
next.prev = t;
25+
}
26+
head.prev = t;
27+
}
28+
cur = next;
29+
}
30+
return head;
31+
}
32+
}

0 commit comments

Comments
 (0)