cousin_sum = level_sum - sibling_sum
算是昨天level-wise BFS的练习
晚安各位
明天 继续卷
一二三四五
def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
cur = root
q = deque()
q.appendleft((root, root.val))
while q:
n = len(q)
tmp, level_sum = [], 0
for _ in range(n):
cur_node, sibling_sum = q.pop()
level_sum += cur_node.val
tmp.append((cur_node, sibling_sum))
next_sibling_sum = sum([(node.val if node is not None else 0) for
node in [cur_node.left, cur_node.right]])
if cur_node.left:
q.appendleft((cur_node.left, next_sibling_sum))
if cur_node.right:
q.appendleft((cur_node.right, next_sibling_sum))
for node, sibling_sum in tmp:
node.val = level_sum-sibling_sum
return root