child pointer to another doubly linked list.
Problem
You are given a multilevel doubly linked list where each node containsprev, next, and child pointers. The child pointer may point to another doubly linked list.
Flatten the list so that all nodes appear in a single-level doubly linked list. The nodes from a child list should appear immediately after the parent node and before the parent's original
next node.
After flattening, every
child pointer must be set to null.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
1 - 2 - 3 - 4 - 5
|
6 - 7
Output
1 - 2 - 3 - 6 - 7 - 4 - 5
Solution
This solution uses Depth-First Search to flatten each child list before continuing with the remaining nodes of the current level.When a node has a
child, we first save its original next node because the child list will be inserted between the current node and its original next node.
We then recursively flatten the child list. The flattened child list is connected after the current node, and the original next part of the list is connected after the end of the flattened child list.
Finally, the
child pointer is set to null. This process continues until the entire multilevel list has been converted into a single doubly linked list.
class Solution {
public Node flatten(Node head) {
if (head == null) {
return null;
}
flattenList(head);
return head;
}
private Node flattenList(Node current) {
Node last = current;
while (current != null) {
Node next = current.next;
if (current.child != null) {
Node childHead = current.child;
Node childTail = flattenList(childHead);
// Connect current node to child list.
current.next = childHead;
childHead.prev = current;
// Connect child list to original next.
if (next != null) {
childTail.next = next;
next.prev = childTail;
}
// Remove child pointer.
current.child = null;
last = childTail;
} else {
last = current;
}
current = next;
}
return last;
}
}
Complexity
Every node is visited and processed once, so the time complexity isO(n), where n is the total number of nodes across all levels.
The algorithm uses recursion for the nested child lists. The auxiliary space complexity is
O(d), where d is the maximum nesting depth of the multilevel list.
Comments
No comments yet. Ask a question or share what helped.