[leetcode] 117. Populating Next Right Pointers in Each Node II @ python

原题

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

解法

BFS, 依次将每层的节点放入列表中, 然后每个列表的节点都指向它下一个节点.

代码

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution(object):
    def connect(self, root):
        """
        :type root: Node
        :rtype: Node
        """
        # base case
        if not root: return None
        q = [root]
        while q:
            for i in range(1, len(q)):
                q[i-1].next = q[i]
            q = [kid for node in q for kid in (node.left, node.right) if kid]
            
        return root

你可能感兴趣的:([leetcode] 117. Populating Next Right Pointers in Each Node II @ python)