Short iterative python solution using constant space

  • 0
    def connect2(root):
        while root:
            while root and not root.left and not root.right:
                root =
            if not root:
            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 =
                if not root:
                curr = root.left if root.left and root.left != prev else root.right
                if root.right is curr:
                    root =
       = curr
                prev = curr
                curr =
            root = next_head

Log in to reply

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