Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 18a808c

Browse files
committedNov 5, 2020
added solution for 430
1 parent 555f2ec commit 18a808c

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.fishercoder.common.classes;
2+
3+
public class DoublyLinkedNode {
4+
public int val;
5+
public DoublyLinkedNode next;
6+
public DoublyLinkedNode prev;
7+
public DoublyLinkedNode child;
8+
public DoublyLinkedNode(int i) {
9+
this.val = i;
10+
}
11+
12+
public int val() {
13+
return val;
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.fishercoder.solutions;
2+
3+
import com.fishercoder.common.classes.DoublyLinkedNode;
4+
5+
/**
6+
* Idea is to implement a recursive strategy by calling the recursiveFlatten() method, recursively on the child node of the parent Node
7+
*
8+
*/
9+
public class _430 {
10+
public static class Solution{
11+
private DoublyLinkedNode recursiveFlatten(DoublyLinkedNode head){
12+
DoublyLinkedNode current = head, tail = head;
13+
while(current != null){
14+
DoublyLinkedNode child = current.child;
15+
DoublyLinkedNode next = current.next;
16+
if(child != null){
17+
DoublyLinkedNode output = recursiveFlatten(child);
18+
output.next = next;
19+
if(next != null)
20+
next.prev = output;
21+
current.next = child;
22+
child.prev = current;
23+
current.child = null;
24+
}
25+
else{
26+
current = next;
27+
}
28+
if(current != null){
29+
tail = current;
30+
}
31+
}
32+
return tail;
33+
}
34+
public DoublyLinkedNode flatten(DoublyLinkedNode head) {
35+
if(head != null)
36+
recursiveFlatten(head);
37+
return head;
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)
Please sign in to comment.