-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsol.py
32 lines (29 loc) · 945 Bytes
/
sol.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
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
# the smallest (first) and the largest (last) nodes
first, last = None, None
def helper(node):
nonlocal last, first
if node:
# left
helper(node.left)
# node
if last:
# link the previous node (last)
# with the current one (node)
last.right = node
node.left = last
else:
# keep the smallest node
# to close DLL later on
first = node
last = node
# right
helper(node.right)
if not root:
return None
helper(root)
# close DLL
last.right = first
first.left = last
return first