蠡口117. Populating Next Right Pointers in Each Node II

Likou continuation 116. This question can not think like a long recursively practice. I think of the hierarchy traversal, can be recycled to do the following:

  1) The data of each layer from left to right in a queue, pop out of the left element, to pre;

  2) If the element is non-empty right-most layer of the element, it does not need to do anything; otherwise, the first elements of pop after the team as a next pre;

  3) around the pre non-empty queue children were added to prepare the next layer operation;

Note that the far right elements of the current layer is not the next lower level of the extreme left, so each cycle only the elements of the current layer assignment, use a for loop can handle that. This question may be used for Solving Li mouth 116.

class Solution(object):
    def connect(self, root):
        """
        :type root: Node
        :rtype: Node
        """
        if root==None: return(None)
        q=collections.deque([root])
        while q:
            size=len(q)
            for i in range(size):
                pre=q.popleft()
                if i<size-1: pre.next=q[0]
                if pre.left: q.append(pre.left)
                if pre.right: q.append(pre.right)
        return(root)

 

Guess you like

Origin www.cnblogs.com/Leisgo/p/11706567.html