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 that the depth of a node is the number of edges in the path from the root node to it.
For example:
Input: root = [5,4,9,1,10,null,7]
Output: [0,0,0,7,7,null,11]
Explanation:
Constraints:
The number of nodes in the tree is in the range [1, 10^5]
.
1 <= Node.val <= 10^4
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return root
root.val = 0 # Root has no cousins, so sum is 0
queue = [root]
while queue:
next_level = []
level_sum = 0
children_values = {}
#First we calculate the level sum and the children's values to be used later
for node in queue:
if node.left:
level_sum += node.left.val
next_level.append(node.left)
if node.right:
level_sum += node.right.val
next_level.append(node.right)
#Second, we modify the children's values based on the level sum
for node in queue:
cousin_sum = level_sum
if node.left:
cousin_sum -= node.left.val
if node.right:
cousin_sum -= node.right.val
if node.left:
node.left.val = cousin_sum
if node.right:
node.right.val = cousin_sum
queue = next_level
return root
Initialization:
None
, return it.Level-Order Traversal:
while queue
loop continues as long as there are nodes to process.next_level
list stores the nodes for the next level.level_sum
calculates the sum of all node values at the current level.Calculating Level Sum:
level_sum
and append the child to next_level
.Updating Node Values:
cousin_sum
by subtracting the left and right child values (if they exist) from level_sum
.cousin_sum
.Moving to the Next Level:
queue
to next_level
to process the next level of the tree.Return Root:
Consider the input root = [5,4,9,1,10,null,7]
None
, the function returns None
without any processing.None
children when computing the cousin_sum
.