Iterative Constant Space O(n) Time Python Solution


  • 0
    L

    Pretty easy to understand solution
    '''
    def connect(root):
    parent = root
    next_parent = None
    last_child = None
    while parent:
    # find first node of next level:
    if not next_parent:
    next_parent = parent.left if parent.left else parent.right

        # connect next level
        if parent.left and parent.right:
            if last_child:
                last_child.next = parent.left
            parent.left.next = parent.right
            last_child = parent.right
        elif parent.left:
            if last_child:
                last_child.next = parent.left
            last_child = parent.left
        elif parent.right:
            if last_child:
                last_child.next = parent.right
            last_child = parent.right
    
        if parent.next:
            parent = parent.next
        else:
            parent = next_parent
            last_child = None
            next_parent = None
    

    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.