Flatten a multi level DLL
Similar copy list problem with random pointer, there is a DLL with child pointers. Some nodes have non-null child pointer. So problem is to create a single DLL with merging the child lists.
This is not a complex problem. I think many can guess that this problem can be solved using recursion.
This can be solved in 3 ways:
- in a while go over list till not None. In a loop if a node is having a child pointer, call the same function recursively by passing child pointer.
- In a recursive function, check if a node is NULL return. add the node to the new list, if the node is having child pointer, call it recursively. if a node having next pointer call it recursively.
- This solution I learnt from solutions approach. This solution uses the stack pointer. Push the head. In a while loop pop the node from the stack and add it to newlist. If a node has next pointer push it. If a node child pointer push it. Note stack is LIFO. As child pointer should be processed before next pointer, we should push child pointer last.
Below is the code for approach 2:
class Solution(object):
def helper(self, head, nc):
if not head:
return nc
nc.child = None
nc.next = head
head.prev = nc
nc = nc.next
# if head.next is not saved in local variable, code is causing a loop
nxt = head.next
nc = self.helper(head.child, nc)
nc = self.helper(nxt, nc)
return nc def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return None
nh = nc = Node(head.val, None, None, None)
nc = self.helper(head.child,nc)
nc = self.helper(head.next,nc)
return nh
stack based solution:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def helper(self, head):
if not head:
return head
#iterative approach using stack
stk = []
stk.append(head)
dh = Node(0, None, head, None)
nc = dh
while stk:
cur = stk.pop()
nc.next = cur
cur.prev = nc
if cur.next:
stk.append(cur.next)
if cur.child:
stk.append(cur.child)
cur.child = None
nc= nc.next
dh.next.prev = None
return dh.next
def flatten(self, head):
return self.helper(head)
In Python, I dont know if a variable is assigned to another pointer pointer variable, does the new variable point to the existing address or it does copy memory.
Please give your comments.