1666. Cousin Totals

In a knockout tournament drawn as a binary tree, two nodes are cousins when they lie on the same level but have different parents. Each node currently stores a score. Replace the score of every node with the sum of the original scores of all its cousins; a node with no cousins (the root, or a node whose level holds only its own sibling group) gets 0.

Every new value must be computed from the original scores, not from values you have already overwritten. Modify the tree in place; the method returns nothing and the judge prints the tree from root afterwards. Comparing each node against every other node of its level costs O(n^2) on wide trees, which is too slow here. Use per-level totals to finish in O(n) time with O(w) extra space, where w is the widest level.

Example 1

Input:
root = [10,4,9,1,6,3,8]
Output:
[0,0,0,11,11,7,7]
Explanation:

The root and the sibling pair 4 and 9 have no cousins and become 0; on the bottom level the groups {1,6} and {3,8} total 7 and 11, so 1 and 6 each become 11 while 3 and 8 each become 7.

Example 2

Input:
root = [4,2,7,5,1,null,3,6]
Output:
[0,0,0,3,3,null,6,0]
Explanation:

Level 2 holds 5, 1 and 3 where 5 and 1 are siblings, so 5 and 1 become 3 and node 3 becomes 5+1=6; level 3 holds only node 6, which has no cousins.

Constraints

1 ≤ nodes ≤ 105; 1 ≤ Node.val ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from root after your method returns.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(w)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…