Tap here to switch tabs
Problem
Submissions

Problem: Cousins in Binary Tree II

Cousins in Binary Tree II replaces each node's value with the sum of values from same-depth nodes with different parents, using zero when no cousins exist, then returns the modified tree.

Statement

Given the root of a binary tree, replace the value of each node with the sum of all its cousins’ values.

Two nodes in a binary tree are considered cousins if they are at the same depth but have different parents.

If a node has no cousins, its value should be replaced with 00.

Return the root of the modified tree.

Constraints:

  • The number of nodes in the tree is in the range [1,105][1, 10^5].

  • 1≤1 \leq Node.val ≤104\leq 10^4

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Cousins in Binary Tree II

Cousins in Binary Tree II replaces each node's value with the sum of values from same-depth nodes with different parents, using zero when no cousins exist, then returns the modified tree.

Statement

Given the root of a binary tree, replace the value of each node with the sum of all its cousins’ values.

Two nodes in a binary tree are considered cousins if they are at the same depth but have different parents.

If a node has no cousins, its value should be replaced with 00.

Return the root of the modified tree.

Constraints:

  • The number of nodes in the tree is in the range [1,105][1, 10^5].

  • 1≤1 \leq Node.val ≤104\leq 10^4