Skip to content

2641. Cousins in Binary Tree II #739

Answered by kovatz
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

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 Tree…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Oct 23, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 23, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants