Python Iterative Accepted Solution


  • 0
    A

    I feel like I need to share this because this is the first time I got accepted for a medium problem w/o looking at the discussion. Please let me know if anything is wrong.

    from collections import deque
    class Solution:
        # @param root, a tree link node
        # @return nothing
        def connect(self, root):
            if root is None: return
            q = deque([root])
            prevRight = None
            while len(q) > 0:
                cur = q.popleft()
                if cur.right is not None:
                    if cur.next is not None:
                        cur.right.next = cur.next.left
                    q.append(cur.right)
                if cur.left is not None:
                    cur.left.next = cur.right
                    q.append(cur.left)
    

Log in to reply
 

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