设置p为根节点,设置判断count,长度为当前层长度
逐个遍历节点,若左右节点存在则加入,随后删除头节点。
当count=1时,为当前层最后一个节点的时候,p指向None。删除头节点,p指向下一层开头
若count != 1,则正常向后指
""" # 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 """ class Solution: def connect(self, root: ‘Node‘) -> ‘Node‘: if not root: return None p = root nexttemp = [p] length = len(nexttemp) count = length while count > 0 : head = nexttemp[0] if count == 1: p.next = None count -= 1 if head.left and head.right: nexttemp.append(head.left) nexttemp.append(head.right) del nexttemp[0] if nexttemp == []: break p = nexttemp[0] length = len(nexttemp) count = length else: p.next = nexttemp[1] count -= 1 if head.left and head.right: nexttemp.append(head.left) nexttemp.append(head.right) del nexttemp[0] p = p.next return root
leetcode-python-填充每个节点的下一个右侧节点指针
原文:https://www.cnblogs.com/cbachen/p/14893872.html