Re: [闲聊] 每日leetcode

楼主: dont   2024-10-23 09:12:16
2641. Cousins in Binary Tree II
## 思路
BFS
每一层都用Hashtable记录同父节点的和
然后再更新值 (= 整层总和 - 同父节点的和)
## Code
```python
class Solution:
def replaceValueInTree(self, root: Optional[TreeNode]) ->
Optional[TreeNode]:
root.val = 0
queue = deque()
if root.left:
queue.append((root, root.left))
if root.right:
queue.append((root, root.right))
while queue:
total = 0
table = defaultdict(int)
for _ in range(len(queue)):
parent, node = queue.popleft()
total += node.val
table[parent] += node.val
if node.left:
queue.append((node, node.left))
if node.right:
queue.append((node, node.right))
for parent in table:
if parent.left:
parent.left.val = total - table[parent]
if parent.right:
parent.right.val = total - table[parent]
return root
```
作者: DJYOMIYAHINA (通通打死)   2024-10-23 09:13:00
别卷了
作者: sustainer123 (caster)   2024-10-23 09:15:00
早早早
楼主: dont   2024-10-23 09:20:00

Links booklink

Contact Us: admin [ a t ] ucptt.com