
Sponsored
Sponsored
In this approach, we utilize a stack to achieve depth-first traversal of the multilevel doubly linked list. We push nodes into the stack starting from the head, along with managing the child nodes as higher priority over next nodes. This ensures that we process all child nodes before moving on to the next nodes.
Time Complexity: O(n) where n is the number of nodes. Each node is visited once.
Space Complexity: O(n) for the stack in the worst case scenario.
1import java.util.Stack;
2
3class Solution {
4 public Node flatten(Node head) {
5 if (head == null) return head;
6
7 Stack<Node> stack = new Stack<>();
8 Node curr = head;
9
10 while (curr != null) {
11 if (curr.child != null) {
12 if (curr.next != null) stack.push(curr.next);
13 curr.next = curr.child;
14 curr.child.prev = curr;
15 curr.child = null;
16 }
17
18 if (curr.next == null && !stack.isEmpty()) {
19 curr.next = stack.pop();
20 if (curr.next != null) curr.next.prev = curr;
21 }
22
23 curr = curr.next;
24 }
25
26 return head;
27 }
28}This Java solution mirrors the previous implementations by leveraging a Stack collection to handle the backtracking required by the multilevel lists. The stack holds the next references to restore them once the child list traversal is complete.
This approach utilizes recursion to handle the traversing and flattening of lists. By inherently using the function call stack, it efficiently manages shifts between the parent and child lists, automatically flattening the entire structure as it recursively resolves each node and its children.
Time Complexity: O(n) due to the necessity to visit each node once.
Space Complexity: O(d) where d is the maximum depth of the children, necessitating stack space for recursion.
public Node Flatten(Node head) {
if (head == null) return head;
FlattenDFS(head);
return head;
}
private Node FlattenDFS(Node node) {
Node curr = node;
Node tail = node;
while (curr != null) {
Node nextNode = curr.next;
if (curr.child != null) {
Node childTail = FlattenDFS(curr.child);
curr.next = curr.child;
curr.child.prev = curr;
curr.child = null;
if (nextNode != null) {
childTail.next = nextNode;
nextNode.prev = childTail;
}
tail = childTail;
} else {
tail = curr;
}
curr = nextNode;
}
return tail;
}
}The C# solution utilizes a recursive strategy with `FlattenDFS` to traverse through nodes, methodically converting multilevel lists into singular level entities, handling pointers between list levels smoothly over recursive detail management.