原题
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上'Populating Next Right Pointers in Each Node II'问题的方法,通过广度优先搜索(BFS),逐层处理二叉树节点,并将同一层的相邻节点的Next指针相互连接。代码使用Python实现,首先检查根节点是否存在,然后利用队列进行层级遍历。
330

被折叠的 条评论
为什么被折叠?



