国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Cousins in Binary Tree II

Cousins in Binary Tree II

Oct 24, 2024 am 07:01 AM

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:

Cousins in Binary Tree II

  • Input: root = [5,4,9,1,10,null,7]
  • Output: [0,0,0,7,7,null,11]
  • Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.
    • Node with value 5 does not have any cousins so its sum is 0.
    • Node with value 4 does not have any cousins so its sum is 0.
    • Node with value 9 does not have any cousins so its sum is 0.
    • Node with value 1 has a cousin with value 7 so its sum is 7.
    • Node with value 10 has a cousin with value 7 so its sum is 7.
    • Node with value 7 has cousins with values 1 and 10 so its sum is 11.

Example 2:

Cousins in Binary Tree II

  • Input: root = [3,1,2]
  • Output: [0,0,0]
  • Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.
    • Node with value 3 does not have any cousins so its sum is 0.
    • Node with value 1 does not have any cousins so its sum is 0.
    • Node with value 2 does not have any cousins so its sum is 0.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 104

Hint:

  1. Use DFS two times.
  2. For the first time, find the sum of values of all the levels of the binary tree.
  3. For the second time, update the value of the node with the sum of the values of the current level - sibling node’s values.

Solution:

The solution uses a Depth-First Search (DFS) approach twice:

  1. First DFS: Calculate the sum of all node values at each level of the tree.
  2. Second DFS: Update each node's value with the sum of its cousins' values by subtracting its siblings' values from the total for that level.

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]
  1. First DFS (Calculate Level Sums):

    • Level 0: 5 → Sum = 5
    • Level 1: 4 9 → Sum = 13
    • Level 2: 1 10 7 → Sum = 18
    • Final levelSums: [5, 13, 18]
  2. Second DFS (Replace Values):

    • At Level 0: 5 has no cousins → Replace with 0.
    • At Level 1:
      • 4 → Cousins = 9 → Replace with 9 (from Level 1 total, no siblings).
      • 9 → Cousins = 4 → Replace with 4.
    • At Level 2:
      • 1 → Cousins = 10 7 = 17 → Replace with 17.
      • 10 → Cousins = 1 7 = 8 → Replace with 8.
      • 7 → Cousins = 1 10 = 11 → Replace with 11.

Output

<?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.

Summary

  • The solution uses two DFS traversals: one for calculating the sums and the other for replacing node values.
  • The logic ensures each node is updated based on its cousin nodes' values while maintaining the structure of the binary tree.

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:

  • LinkedIn
  • GitHub

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles