116. Populating Next Right Pointers in Each Node 层次遍历 队列 python

116. Populating Next Right Pointers in Each Node 层次遍历 队列 python_第1张图片116. Populating Next Right Pointers in Each Node 层次遍历 队列 python_第2张图片

题目搬运者

https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/

思路 层次遍历

在层次遍历的过程中将我们将二叉树每一层的节点拿出来遍历并连接
用size 在记录每一次层数目,在 i 小于size 的情况下,用到完美二叉树的定义,都是可以直接连接que队列中的头元素。
而一次while就是一层.

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

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

你可能感兴趣的:(leetcode,python,leetcode,广度搜索)