BFS using two dequeues


  • 0
    C

    from collections import deque
    class Solution(object):

    def connect(self, root):
        """
        :type root: TreeLinkNode
        :rtype: nothing
        """
        if not root:
            return None
        q1 = deque([root])
        q2 = deque([])
        while q1:
            cur = q1.popleft()
            if cur.left:
                q2.append(cur.left)
            if cur.right:
                q2.append(cur.right)
            if not q1:
                cur.next = None
                q1,q2=q2,q1
            else:
                cur.next = q1[0]

Log in to reply
 

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