Concise 8-liner in Python, O(1) space

  • 0

    I use a dummy pre node to chain nodes level by level, and I reuse the same one for each level.

    class Solution(object):
        def connect(self, root):
            pre = TreeNode(0)
            while root:
      , cur = None, pre
                while root:
                    for kid in filter(None, [root.left, root.right]):
               = cur = kid
                    root =
                root =

Log in to reply

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