Python O(1) space with O(n) time


  • 0
    A
    def connect(self, root):
        if not root:
            return
        
        root.next = None
        head = root
        prt2 = root
        
        while head:
            nextLevel = False
            prt2 = head
            head = None
            pre = None
            while prt2:
                if prt2.left:
                    if not head:
                        head = prt2.left
                    if pre:
                        pre.next = prt2.left
                        pre = pre.next
                    if not pre:
                        pre = prt2.left
                if prt2.right:
                    if not head:
                        head = prt2.right
                    if pre:
                        pre.next = prt2.right
                        pre = pre.next
                    if not pre:
                        pre = prt2.right
                prt2 = prt2.next
            
            if pre:
                pre.next = None

Log in to reply
 

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