Given the root of a binary tree, your task is to transform each node by replacing its value with the sum of all its cousins' values.

What are cousins? Two nodes in a binary tree are considered cousins if they satisfy two conditions:

  • They are at the same depth (same level) in the tree
  • They have different parents

The depth of a node is defined as the number of edges in the path from the root to that node. The root has depth 0.

Goal: Return the root of the modified tree where each node's value is replaced by the sum of its cousins' values. If a node has no cousins, its value becomes 0.

Example: If nodes A and B are cousins with values 3 and 7, and node C is also their cousin with value 2, then A's new value becomes 7+2=9, B's new value becomes 3+2=5, and C's new value becomes 3+7=10.

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [5,4,9,1,10,null,7]
โ€บ Output: [0,0,0,7,7,null,11]
๐Ÿ’ก Note: Root (5) has no cousins โ†’ 0. Level 1 nodes (4,9) have no cousins โ†’ both 0. Level 2: nodes 1,10 are cousins of 7, so 1โ†’7, 10โ†’7. Node 7 is cousin of 1,10, so 7โ†’1+10=11.
example_2.py โ€” Smaller Tree
$ Input: root = [3,1,2]
โ€บ Output: [0,0,0]
๐Ÿ’ก Note: Root (3) has no cousins โ†’ 0. Nodes 1 and 2 are at the same level but are siblings (same parent), not cousins โ†’ both 0.
example_3.py โ€” Single Node
$ Input: root = [1]
โ€บ Output: [0]
๐Ÿ’ก Note: Single node tree - the root has no cousins, so its value becomes 0.

Constraints

  • The number of nodes in the tree is in the range [1, 105]
  • 1 โ‰ค Node.val โ‰ค 104
  • Tree structure: The tree can be any valid binary tree structure
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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