Given the root of a binary tree, your task is to transform each node by replacing its value with the sum of all its cousins' values.
What are cousins? Two nodes in a binary tree are considered cousins if they satisfy two conditions:
- They are at the same depth (same level) in the tree
- They have different parents
The depth of a node is defined as the number of edges in the path from the root to that node. The root has depth 0.
Goal: Return the root of the modified tree where each node's value is replaced by the sum of its cousins' values. If a node has no cousins, its value becomes 0.
Example: If nodes A and B are cousins with values 3 and 7, and node C is also their cousin with value 2, then A's new value becomes 7+2=9, B's new value becomes 3+2=5, and C's new value becomes 3+7=10.
Input & Output
Constraints
- The number of nodes in the tree is in the range [1, 105]
- 1 โค Node.val โค 104
- Tree structure: The tree can be any valid binary tree structure