看板 Marginalman
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 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.229.37.69 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1729698092.A.2B8.html