Cousins in Binary Tree II

Medium Topics Company Tags

Replace each node's value with the sum of the original values of its cousins, and return the root of the modified tree.

Cousins are nodes at the same depth that have different parents. A node is not its own cousin, and its siblings are not its cousins. The root has no cousins, so its new value is 0. All replacements use the values from before any changes.

Keep the tree's parent-child links unchanged. Examples use level-order arrays, with null for missing children.

Example 1:

Cousins in Binary Tree II, example 1: illustration of the example

Input: root = [8,2,6,3,5,7,1]

Output: [0,0,0,8,8,8,8]

Explanation: The root and its two children have no cousins, so they become 0. At depth 2, nodes 3 and 5 each get 7 + 1 = 8, while nodes 7 and 1 each get 3 + 5 = 8.

Example 2:

Cousins in Binary Tree II, example 2: illustration of the example

Input: root = [4,2,9,null,6,3]

Output: [0,0,0,null,3,6]

Explanation: The root and depth-1 nodes become 0. Node 6 and node 3 have different parents at depth 2, so their new values are 3 and 6 respectively. The missing child stays missing.

Example 3:

Cousins in Binary Tree II, example 3: illustration of the example

Input: root = [10]

Output: [0]

Explanation: A one-node tree has no cousins. Its only value becomes 0.

Constraints:

  • The tree contains between 1 and 100000 nodes.
  • 1 <= Node.val <= 10000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.