Skip to main content
LeetCode 2641, Medium. Topics: Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

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
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
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, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026