|
| 1 | +<h2><a href="https://leetcode.com/problems/cousins-in-binary-tree-ii/">2641. Cousins in Binary Tree II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, replace the value of each node in the tree with the <strong>sum of all its cousins' values</strong>.</p> |
| 2 | + |
| 3 | +<p>Two nodes of a binary tree are <strong>cousins</strong> if they have the same depth with different parents.</p> |
| 4 | + |
| 5 | +<p>Return <em>the </em><code>root</code><em> of the modified tree</em>.</p> |
| 6 | + |
| 7 | +<p><strong>Note</strong> that the depth of a node is the number of edges in the path from the root node to it.</p> |
| 8 | + |
| 9 | +<p> </p> |
| 10 | +<p><strong class="example">Example 1:</strong></p> |
| 11 | +<img alt="" src="https://assets.leetcode.com/uploads/2023/01/11/example11.png" style="width: 571px; height: 151px;"> |
| 12 | +<pre><strong>Input:</strong> root = [5,4,9,1,10,null,7] |
| 13 | +<strong>Output:</strong> [0,0,0,7,7,null,11] |
| 14 | +<strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. |
| 15 | +- Node with value 5 does not have any cousins so its sum is 0. |
| 16 | +- Node with value 4 does not have any cousins so its sum is 0. |
| 17 | +- Node with value 9 does not have any cousins so its sum is 0. |
| 18 | +- Node with value 1 has a cousin with value 7 so its sum is 7. |
| 19 | +- Node with value 10 has a cousin with value 7 so its sum is 7. |
| 20 | +- Node with value 7 has cousins with values 1 and 10 so its sum is 11. |
| 21 | +</pre> |
| 22 | + |
| 23 | +<p><strong class="example">Example 2:</strong></p> |
| 24 | +<img alt="" src="https://assets.leetcode.com/uploads/2023/01/11/diagram33.png" style="width: 481px; height: 91px;"> |
| 25 | +<pre><strong>Input:</strong> root = [3,1,2] |
| 26 | +<strong>Output:</strong> [0,0,0] |
| 27 | +<strong>Explanation:</strong> The diagram above shows the initial binary tree and the binary tree after changing the value of each node. |
| 28 | +- Node with value 3 does not have any cousins so its sum is 0. |
| 29 | +- Node with value 1 does not have any cousins so its sum is 0. |
| 30 | +- Node with value 2 does not have any cousins so its sum is 0. |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p> </p> |
| 34 | +<p><strong>Constraints:</strong></p> |
| 35 | + |
| 36 | +<ul> |
| 37 | + <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> |
| 38 | + <li><code>1 <= Node.val <= 10<sup>4</sup></code></li> |
| 39 | +</ul> |
| 40 | +</div> |
0 commit comments