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


  • 0
    O

    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:
                pre.next, cur = None, pre
                while root:
                    for kid in filter(None, [root.left, root.right]):
                        cur.next = cur = kid
                    root = root.next
                root = pre.next
    

Log in to reply
 

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