class Solution:
    def connect(self, node):
        if not node:
            return
        
        level = [node]

        while level:
            prev = None
            next_level = []
            
            for node in level:
                if prev:
                    prev.next = node
                
                prev = node

                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            
            level = next_level
        