Concise python solution, 9 lines, space O(1)

  • 9

    level by level traversal with a dummy head prekid.

    root is in the current level, and kid is in the next level. is the head in the kid level

    kid = or kid : Update kid ONLY when we actually find its next node

    runtime is around 96ms with a best runtime 88ms.

    def connect(self, root):
        prekid = kid = TreeLinkNode(0)
        while root:
            while root:
       = root.left
                kid = or kid
       = root.right
                kid = or kid
                root =
            root, kid =, prekid

  • 0

    @cmc The best python solution I see for this question.

Log in to reply

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