Home > Article > Backend Development > Cousins in Binary Tree II
2641. Cousins in Binary Tree II
Difficulty: Medium
Topics: Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree
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:
Example 2:
Constraints:
Hint:
Solution:
The solution uses a Depth-First Search (DFS) approach twice:
Let's implement this solution in PHP: 2641. Cousins in Binary Tree II
<?php // Definition for a binary tree node. class TreeNode { public $val = null; public $left = null; public $right = null; public function __construct($val = 0, $left = null, $right = null) { $this->val = $val; $this->left = $left; $this->right = $right; } } class Solution { /** * @param TreeNode $root * @return TreeNode */ public function replaceValueInTree($root) { ... ... ... /** * go to ./solution.php */ } /** * DFS to calculate the sum of node values at each level. * @param $root - current node * @param $level - current depth level in the tree * @param $levelSums - array holding the sum of values at each level * @return void */ private function dfs($root, $level, &$levelSums) { ... ... ... /** * go to ./solution.php */ } /** * DFS to replace the node values with the sum of cousins' values. * @param $root - current node in the original tree * @param $level - current depth level in the tree * @param $curr - node being modified in the new tree * @param $levelSums - array holding the sum of values at each level * @return mixed */ private function replace($root, $level, $curr, $levelSums) { ... ... ... /** * go to ./solution.php */ } } // Helper function to print the tree (for testing purpose) function printTree($root) { if ($root === null) return []; $result = []; $queue = [$root]; while (!empty($queue)) { $node = array_shift($queue); if ($node !== null) { $result[] = $node->val; $queue[] = $node->left; $queue[] = $node->right; } else { $result[] = null; } } // Remove trailing null values for clean output while (end($result) === null) { array_pop($result); } return $result; } // Example usage: // Tree: [5,4,9,1,10,null,7] $root = new TreeNode(5); $root->left = new TreeNode(4); $root->right = new TreeNode(9); $root->left->left = new TreeNode(1); $root->left->right = new TreeNode(10); $root->right->right = new TreeNode(7); $solution = new Solution(); $modifiedTree = $solution->replaceValueInTree($root); print_r(printTree($modifiedTree)); // Output: [0, 0, 0, 7, 7, null, 11] ?> <h3> Breakdown of the Code </h3> <h4> 1. replaceValueInTree Method </h4> <ul> <li>This is the main method that initializes the process.</li> <li>It creates an empty array, $levelSums, to hold the sum of values at each level.</li> <li>It calls the first DFS to populate $levelSums and then calls the second DFS to replace the values in the tree.</li> </ul> <h4> 2. dfs Method (First DFS) </h4> <ul> <li> <p><strong>Parameters:</strong></p> <ul> <li> $root: Current node.</li> <li> $level: Current depth level of the tree.</li> <li> &$levelSums: Reference to the array where sums will be stored.</li> </ul> </li> <li><p><strong>Base Case:</strong> If the node is null, return.</p></li> <li><p>If the current level's sum is not initialized (i.e., the level does not exist in the array), initialize it to 0.</p></li> <li><p>Add the current node's value to the sum for its level.</p></li> <li><p>Recursively call dfs for the left and right children, incrementing the level by 1.</p></li> </ul> <h4> 3. replace Method (Second DFS) </h4> <ul> <li> <p><strong>Parameters:</strong></p> <ul> <li> $root: Current node.</li> <li> $level: Current depth level.</li> <li> $curr: Current node in the modified tree.</li> <li> $levelSums: The array with sums for each level.</li> </ul> </li> <li> <p>Calculate the sum of cousins' values:</p> <ul> <li>Get the total sum for the next level.</li> <li>Subtract the values of the current node's children (siblings) from this total to get the cousins' sum.</li> </ul> </li> <li><p>If the left child exists, create a new TreeNode with the cousins' sum and recursively call replace for it.</p></li> <li><p>If the right child exists, do the same for the right child.</p></li> </ul> <h3> Example Walkthrough </h3> <p>Let's use the first example from the prompt:</p> <h4> Input </h4> <pre class="brush:php;toolbar:false">root = [5,4,9,1,10,null,7]
First DFS (Calculate Level Sums):
Second DFS (Replace Values):
<?php // Definition for a binary tree node. class TreeNode { public $val = null; public $left = null; public $right = null; public function __construct($val = 0, $left = null, $right = null) { $this->val = $val; $this->left = $left; $this->right = $right; } } class Solution { /** * @param TreeNode $root * @return TreeNode */ public function replaceValueInTree($root) { ... ... ... /** * go to ./solution.php */ } /** * DFS to calculate the sum of node values at each level. * @param $root - current node * @param $level - current depth level in the tree * @param $levelSums - array holding the sum of values at each level * @return void */ private function dfs($root, $level, &$levelSums) { ... ... ... /** * go to ./solution.php */ } /** * DFS to replace the node values with the sum of cousins' values. * @param $root - current node in the original tree * @param $level - current depth level in the tree * @param $curr - node being modified in the new tree * @param $levelSums - array holding the sum of values at each level * @return mixed */ private function replace($root, $level, $curr, $levelSums) { ... ... ... /** * go to ./solution.php */ } } // Helper function to print the tree (for testing purpose) function printTree($root) { if ($root === null) return []; $result = []; $queue = [$root]; while (!empty($queue)) { $node = array_shift($queue); if ($node !== null) { $result[] = $node->val; $queue[] = $node->left; $queue[] = $node->right; } else { $result[] = null; } } // Remove trailing null values for clean output while (end($result) === null) { array_pop($result); } return $result; } // Example usage: // Tree: [5,4,9,1,10,null,7] $root = new TreeNode(5); $root->left = new TreeNode(4); $root->right = new TreeNode(9); $root->left->left = new TreeNode(1); $root->left->right = new TreeNode(10); $root->right->right = new TreeNode(7); $solution = new Solution(); $modifiedTree = $solution->replaceValueInTree($root); print_r(printTree($modifiedTree)); // Output: [0, 0, 0, 7, 7, null, 11] ?>
This step-by-step replacement based on cousin values results in the modified tree as shown in the example.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Cousins in Binary Tree II. For more information, please follow other related articles on the PHP Chinese website!