-
Notifications
You must be signed in to change notification settings - Fork 17
/
flatten-a-multilevel-doubly-linked-list.py
59 lines (44 loc) · 1.34 KB
/
flatten-a-multilevel-doubly-linked-list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
stack = [None]
node = head
while stack:
while node:
node_prev = node
if node.child:
stack.append(node.next)
node.next = node.child
node.child.prev = node
node.child = None
node = node.next
right = stack.pop()
if right:
node_prev.next = right
right.prev = node_prev
node = right
return head
def flatten_recursive(self, head: 'Node') -> 'Node':
def dive(left, node, right):
if left:
node.prev = left
left.next = node
left.child = None
while node:
node_prev, node_next = node, node.next
if node.child:
dive(node, node.child, node.next)
node = node_next
if right:
node_prev.next = right
right.prev = node_prev
dive(None, head, None)
return head