Short iterative python solution using constant space


  • 0
    Y
    def connect2(root):
        while root:
            while root and not root.left and not root.right:
                root = root.next
            if not root:
                break
            next_head = root.left if root.left else root.right
            prev = next_head
            curr = None
            while True:
                while root and (not root.left or root.left is prev) and (not root.right or root.right is prev):
                    root = root.next
                if not root:
                    break
                curr = root.left if root.left and root.left != prev else root.right
                if root.right is curr:
                    root = root.next
                prev.next = curr
                prev = curr
                curr = curr.next
            root = next_head

Log in to reply
 

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