Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Cousins in Binary Tree II

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2641" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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: 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: 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

Explanation

Here's an efficient solution to replace each node's value with the sum of its cousins' values in a binary tree:

  • Level-Order Traversal: Perform a level-order traversal of the tree to process nodes level by level.
  • Cousin Sum Calculation: For each level, calculate the sum of all node values at that level. Then, for each node, subtract its parent's children's values from the level sum to obtain the sum of its cousins' values. If a node does not have cousins (e.g., root or single child at a level), its value becomes 0.
  • In-Place Modification: Modify the node values directly during the traversal.

  • Runtime & Storage Complexity: O(N) time complexity, where N is the number of nodes in the tree. O(W) storage complexity where W is the maximum width of the tree (the maximum number of nodes at any level), due to the queue used in the level order traversal. In the worst case (a complete binary tree), W can be N/2, so we can also express this as O(N).

Code

    from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def replace_with_cousin_sum(root):
    if not root:
        return None

    queue = deque([root])

    while queue:
        level_size = len(queue)
        level_nodes = []

        for _ in range(level_size):
            node = queue.popleft()
            level_nodes.append(node)

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        # Calculate level sum
        level_sum = sum(node.val for node in level_nodes)

        #Update node values with sum of cousins
        for node in level_nodes:
            parent_sum = 0
            # Find the parent and get its children's sum, if they exist
            for other_node in level_nodes:
                if other_node != node:
                    parent_sum += other_node.val

            node.val = level_sum - parent_sum


            if level_size <=1:
                node.val = 0    

    return root

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Cousins in Binary Tree II