117. 填充每个节点的下一个右侧节点指针 II - 力扣(LeetCode)
python
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
from collections import deque
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
queue = deque([root])
while queue:
size = len(queue)
prev = None # 记录上一节点
for i in range(size):
node = queue.popleft()
if prev:
prev.next = node # 连接前一个节点的 next
prev = node # 更新 prev
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# 该层最后一个节点的 next 置为 None
prev.next = None
return root