Cousins in Binary Tree II - 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: 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code