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

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87969247

原题

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

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87969247
今日推荐