https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
层序遍历,只不过在遍历同一层的时候,每次将当前节点的next指向队列中下一个即将遍历的节点。
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root == None:
return
if root.left == None and root.right == None:
root.next = None
return root
"""就是层序遍历"""
queue = [root] """需要取子节点的队列"""
nextQueue = [] """子节点存放的队列,表示在同一层"""
self.root = root
while queue:
cur = queue.pop(0) # 当前从queue中取出的节点
if cur.left: nextQueue.append(cur.left)
if cur.right: nextQueue.append(cur.right)
if queue == []:
cur.next = None
queue += nextQueue
nextQueue = []
else:
cur.next = queue[0]
return self.root