forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_430.java
82 lines (75 loc) · 2.4 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.fishercoder.solutions;
import com.fishercoder.common.classes.DoublyLinkedNode;
/**
* Idea is to implement a recursive strategy by calling the recursiveFlatten() method, recursively on the child node of the parent Node
*
*/
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 Solution {
private DoublyLinkedNode recursiveFlatten(DoublyLinkedNode head){
DoublyLinkedNode current = head, tail = head;
while(current != null){
DoublyLinkedNode child = current.child;
DoublyLinkedNode next = current.next;
if(child != null){
DoublyLinkedNode output = recursiveFlatten(child);
output.next = next;
if(next != null)
next.prev = output;
current.next = child;
child.prev = current;
current.child = null;
}
else{
current = next;
}
if(current != null){
tail = current;
}
}
return tail;
}
public DoublyLinkedNode flatten(DoublyLinkedNode head) {
if(head != null)
recursiveFlatten(head);
return head;
}
}
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;
}
}
}