from collections import deque
def connect(root: 'Optional[Node]') -> 'Optional[Node]':
q, level = deque(), 0
q.append((root, level))
while q:
node, i = q.popleft()
# if we start a new level that means that prec_node was the rightest of its level and should point to None
if i != level:
prec_node.next, level = None, i
# otherwise the left neighbour (pop just before this one) point to current node (not for 1st node)
elif i > 0:
prec_node.next = node
# set prec_node to node and add its children in the queue with their corresponding level
if node:
prec_node = node
q.extend(((node.left, i+1), (node.right, i+1)))
return(root)