diff --git a/README.md b/README.md index fb425128e1..28620fe053 100644 --- a/README.md +++ b/README.md @@ -1421,6 +1421,7 @@ _If you like this project, please leave me a star._ ★ | 2 |[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [Solution](../master/src/main/java/com/fishercoder/solutions/_2.java) | | Medium | LinkedList | 1 |[Two Sum](https://leetcode.com/problems/two-sum/)| [Java](../master/src/main/java/com/fishercoder/solutions/_1.java), [C++](../master/cpp/_1.cpp), [Javascript](../master/javascript/_1.js) | [:tv:](https://www.youtube.com/watch?v=kPXOr6pW8KM&t=) | Easy | HashMap + ## Database | # | Title | Solutions | Video | Difficulty | Tag diff --git a/src/main/java/com/fishercoder/common/classes/DoublyLinkedNode.java b/src/main/java/com/fishercoder/common/classes/DoublyLinkedNode.java new file mode 100644 index 0000000000..169e9a53c9 --- /dev/null +++ b/src/main/java/com/fishercoder/common/classes/DoublyLinkedNode.java @@ -0,0 +1,15 @@ +package com.fishercoder.common.classes; + +public class DoublyLinkedNode { + public int val; + public DoublyLinkedNode next; + public DoublyLinkedNode prev; + public DoublyLinkedNode child; + public DoublyLinkedNode(int i) { + this.val = i; + } + + public int val() { + return val; + } +} diff --git a/src/main/java/com/fishercoder/solutions/_430.java b/src/main/java/com/fishercoder/solutions/_430.java index fb66d8b8dd..487281efa7 100644 --- a/src/main/java/com/fishercoder/solutions/_430.java +++ b/src/main/java/com/fishercoder/solutions/_430.java @@ -1,5 +1,12 @@ 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 { /** @@ -28,6 +35,36 @@ private Node dfs(Node prev, Node curr) { 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;