Ctrl K

Replace With Cousin Sums

Medium
You get the root of a binary tree. Two nodes are **cousins** if they sit at the same depth but have different parents (depth is the number of edges from the root to the node). Replace the value of every node with the sum of the values of all its cousins. A node without cousins gets 0. All replacements are based on the original values. Return the root of the modified tree.
Example 1
root=tree_node([6, 2, 8, 1, 3, None, 5]) → [0, 0, 0, 5, 5, None, 4]

The root and nodes 2 and 8 have no cousins, so they become 0. At depth 2, nodes 1 and 3 are children of 2 and node 5 is a child of 8. So 1 and 3 become 5, and 5 becomes 1 + 3 = 4.

Example 2
root=tree_node([4, 7, None, 2, 9]) → [0, 0, None, 0, 0]

At every depth all nodes share one parent, so nobody has cousins and every value becomes 0.

Example 3
root=tree_node([1, 10, 20, 3, None, 4, 6]) → [0, 0, 0, 10, None, 3, 3]
Constraints
  • The tree has between 1 and 10⁵ nodes
  • 1 ≤ Node.val ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Columns, Top Down MediumSmallest Cover of the Bottom Row MediumWhere the Deepest Leaves Meet MediumHops Between Two Keys MediumSpread Through the Tree Medium
loading Python…
Input
root=tree_node([6, 2, 8, 1, 3, None, 5])
Expected
[0, 0, 0, 5, 5, None, 4]

Run checks the first 3 tests in your browser. Submit checks all 75 tests on the server, hidden ones included.