-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_430.java
45 lines (40 loc) · 1.16 KB
/
_430.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.fishercoder.solutions.firstthousand;
public class _430 {
public static class Solution1 {
/*
* credit: https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/solution/
*/
public Node flatten(Node head) {
if (head == null) {
return null;
}
Node pre = new Node(-1, null, head, null);
dfs(pre, head);
pre.next.prev = null;
return pre.next;
}
private Node dfs(Node prev, Node curr) {
if (curr == null) {
return prev;
}
curr.prev = prev;
prev.next = curr;
Node next = curr.next;
Node tail = dfs(curr, curr.child);
curr.child = null;
return dfs(tail, next);
}
}
public static class Node {
public int val;
public Node prev;
public Node next;
public Node child;
public Node(int val, Node prev, Node next, Node child) {
this.val = val;
this.prev = prev;
this.next = next;
this.child = child;
}
}
}