Cousins in Binary Tree II

MediumTreeslevel order

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, replace every node's value with the sum of the values of its **cousins**, and return the root of the modified tree. Two nodes are cousins when they are at the same depth but have different parents. Siblings (nodes sharing a parent) are not cousins, and a node is not its own cousin. A node with no cousins gets the value 0; in particular the root always becomes 0. All sums use the tree's original values. The result is graded in level order.

Examples

Input: root = [1,2,3,4,5,6]
Output: [0,0,0,6,6,9]
At depth 2, 4 and 5 share parent 2, so each gets 6 (their only cousin). 6 gets 4 + 5 = 9. Depth 1 nodes are siblings and get 0.
Input: root = [3,1,2]
Output: [0,0,0]
1 and 2 are siblings, so neither has a cousin.

Constraints

  • 1 <= number of nodes <= 10^5
  • 1 <= Node.val <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More level order problems