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: The depth of a node is the number of edges in the path from the root node to it.

Input & Output

Example 1 — Basic Tree
$ Input: root = [5,4,9,1,10,null,7]
Output: [0,0,0,7,7,null,11]
💡 Note: Root has no cousins (0). Level 1: nodes 4,9 have no cousins since they're the only nodes at that level (0,0). Level 2: node 1 has cousin 7 (value 7), node 10 has cousin 7 (value 7), node 7 has cousins 1,10 (sum = 11).
Example 2 — Single Node
$ Input: root = [3]
Output: [0]
💡 Note: Single node has no cousins, so its value becomes 0.
Example 3 — Complete Binary Tree
$ Input: root = [1,2,3,4,5,6,7]
Output: [0,0,0,16,16,16,16]
💡 Note: Level 2: all nodes (4,5,6,7) are cousins of each other. Each gets sum of the other three: 4+5+6+7-own_value. Node 4: 22-6=16, similar for others.

Constraints

  • The number of nodes in the tree is in the range [1, 105]
  • 1 ≤ Node.val ≤ 104

Visualization

Tap to expand
INPUT TREEALGORITHMRESULT5491107Original: [5,4,9,1,10,null,7]1Level 0: Root = 022Level 1: Sum = 13333Level 2: CalculateBFS processes each level:1. Calculate level sum2. Cousin = level_sum - sibling_sum3. Update node values0007711Result: [0,0,0,7,7,null,11]Key Insight:Use BFS to process levels efficiently. For each node, cousin sum = level sum - sibling sum.This avoids the need to explicitly track parent-child relationships and reduces complexity.TutorialsPoint - Cousins in Binary Tree II | BFS Level Processing
Asked in
Meta 15 Amazon 12 Microsoft 8 Apple 6
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen