Cousins in Binary Tree II

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.

Example 1
        5                   0
       / \                 / \
      4   9       ->      0   0
     / \   \             / \   \
    1  10   7           7   7  11
Inputroot = [5,4,9,1,10,null,7]
Output[0,0,0,7,7,null,11]
Node 5, nodes 4 and 9, and the root-level/parent-sharing nodes have no cousins where applicable, while nodes 1 and 10 each have cousin 7 and node 7 has cousins 1 and 10.
Example 2
        3             0
       / \     ->    / \
      1   2         0   0
Inputroot = [3,1,2]
Output[0,0,0]
Each node has no cousins, so every value is replaced with 0.

Constraints

  • The number of nodes in the tree is in the range [1, 10^5].
  • 1 <= Node.val <= 10^4

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate