My Python Solution, constant space


  • 0
    C
    class Solution(object):
        def connect(self, root):
            """
            :type root: TreeLinkNode
            :rtype: nothing
            """
            if root is None:
                return
            cursor = root
            next_node = None
            while cursor is not None:
                if cursor.left is not None or cursor.right is not None:
                    last = None
                    if cursor.left and cursor.right:
                        cursor.left.next = cursor.right
                        last = cursor.right
                        if next_node is None:
                            next_node = cursor.left
                    elif cursor.left is None:
                        last = cursor.right
                        if next_node is None:
                            next_node = cursor.right
                    else:
                        last = cursor.left
                        if next_node is None:
                            next_node = cursor.left
                    n = cursor.next
                    while n is not None:
                        if n.left:
                            last.next = n.left
                            break
                        elif n.right:
                            last.next = n.right
                            break
                        else:
                            n = n.next
                cursor = cursor.next
            self.connect(next_node)

Log in to reply
 

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