Re: [闲聊] 每日leetcode

楼主: DJYOMIYAHINA (通通打死)   2024-10-23 23:41:30
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
作者: oin1104 (是oin的说)   2024-10-23 23:49:00
宝 我来当你的枕头了

Links booklink

Contact Us: admin [ a t ] ucptt.com