> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Cousins in Binary Tree II Python Solution

> Tested Python solution for LeetCode 2641 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 2641, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/cousins-in-binary-tree-ii/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2641   # by problem number
lcpy gen -s cousins_in_binary_tree_ii   # by problem name
```

## Problem

Given the `root` of a binary tree, replace the value of each node in the tree with the **sum of all its cousins' values**.

Two nodes of a binary tree are **cousins** if they have the same depth with different parents.

Return the root of the modified tree.

Note that the depth of a node is the number of edges in the path from the root node to it.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2023/01/11/example11.png)

```
Input: root = [5,4,9,1,10,null,7]
Output: [0,0,0,7,7,null,11]
```

**Explanation:** Node with value 5 does not have any cousins so its sum is 0. Node with value 4 does not have any cousins so its sum is 0. Node with value 9 does not have any cousins so its sum is 0. Node with value 1 has a cousin with value 7 so its sum is 7. Node with value 10 has a cousin with value 7 so its sum is 7. Node with value 7 has cousins with values 1 and 10 so its sum is 11.

![Example 2](https://assets.leetcode.com/uploads/2023/01/11/diagram33.png)

```
Input: root = [3,1,2]
Output: [0,0,0]
```

**Explanation:** Node with value 3 does not have any cousins so its sum is 0. Node with value 1 does not have any cousins so its sum is 0. Node with value 2 does not have any cousins so its sum is 0.

### Constraints

* The number of nodes in the tree is in the range \[1, 10^5].
* 1 \<= Node.val \<= 10^4

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/cousins_in_binary_tree_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/cousins_in_binary_tree_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(n)
    def replace_value_in_tree(self, root: TreeNode[int] | None) -> TreeNode[int] | None:
        if root is None:
            return None

        queue: deque[TreeNode[int]] = deque([root])
        root.val = 0

        while queue:
            next_sum = 0
            for node in queue:
                for child in (node.left, node.right):
                    if child is not None:
                        next_sum += child.val

            for _ in range(len(queue)):
                node = queue.popleft()
                left, right = node.left, node.right
                child_sum = 0
                if left is not None:
                    child_sum += left.val
                if right is not None:
                    child_sum += right.val
                for child in (left, right):
                    if child is not None:
                        child.val = next_sum - child_sum
                        queue.append(child)

        return root
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.