---
# System prepended metadata

title: LC 2641. Cousins in Binary Tree II
tags: [BFS, medium, leedcode, DFS, python]

---

# LC 2641. Cousins in Binary Tree II

### [Problem link](https://leetcode.com/problems/cousins-in-binary-tree-ii/)

###### tags: `leedcode` `python` `medium` `DFS` `BFS`

Given the <code>root</code> 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 <code>root</code> 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.

**Example 1:** 
<img alt="" src="https://assets.leetcode.com/uploads/2023/01/11/example11.png" style="width: 571px; height: 151px;" />
```
Input: root = [5,4,9,1,10,null,7]
Output: [0,0,0,7,7,null,11]
Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.
- 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:** 
<img alt="" src="https://assets.leetcode.com/uploads/2023/01/11/diagram33.png" style="width: 481px; height: 91px;" />
```
Input: root = [3,1,2]
Output: [0,0,0]
Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.
- 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 <code>[1, 10<sup>5</sup>]</code>.
- <code>1 <= Node.val <= 10<sup>4</sup></code>


## Solution 1 - DFS
#### Python
```python=
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(cur, depth):
            if not cur:
                return
            level_sum[depth] += cur.val
            if cur.left:
                par2sum[cur] += cur.left.val
            if cur.right:
                par2sum[cur] += cur.right.val
            dfs(cur.left, depth + 1)
            dfs(cur.right, depth + 1)

        def dfs2(cur, par, depth):
            if not cur:
                return
            cur.val = level_sum[depth] - par2sum[par]
            dfs2(cur.left, cur, depth + 1)
            dfs2(cur.right, cur, depth + 1)
            
        level_sum = defaultdict(int)
        par2sum = defaultdict(int)

        dfs(root, 0)
        dfs2(root, None, 0)
        root.val = 0
        
        return root
```

## Solution 2 - BFS
#### C++
```cpp=
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* replaceValueInTree(TreeNode* root) {
        queue<TreeNode *> q;
        q.push(root);
        int sum = root->val;
        while (!q.empty()) {
            int childrenSum = 0;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode *node = q.front();
                q.pop();
                node->val = sum - node->val;
                if (node->left) {
                    q.push(node->left);
                    childrenSum += node->left->val;
                }
                if (node->right) {
                    q.push(node->right);
                    childrenSum += node->right->val;
                }
                if (node->left && node->right) {
                    int tmp = node->left->val + node->right->val;
                    node->left->val = tmp;
                    node->right->val = tmp;
                }
            }
            sum = childrenSum;
        }
        return root;
    }
};
```

>### Complexity
>n = number of nodes
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(n)             |
>| Solution 2  | O(n)            | O(n)             |

## Note
sol2:
在遍歷這一層時計算child的和.
