Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2641: Cousins in Binary Tree II

In this guide, we solve Leetcode #2641 Cousins in Binary Tree II in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree

Intuition

Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.

By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.

Approach

Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.

This keeps the solution linear while remaining easy to explain in an interview setting.

Steps:

  • Initialize a hash map for seen items or counts.
  • Iterate through the input, querying/updating the map.
  • Return the first valid result or the final computed value.

Example

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.

Python Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def dfs1(root: Optional[TreeNode], depth: int): if root is None: return if len(s) <= depth: s.append(0) s[depth] += root.val dfs1(root.left, depth + 1) dfs1(root.right, depth + 1) def dfs2(root: Optional[TreeNode], depth: int): sub = (root.left.val if root.left else 0) + ( root.right.val if root.right else 0 ) depth += 1 if root.left: root.left.val = s[depth] - sub dfs2(root.left, depth) if root.right: root.right.val = s[depth] - sub dfs2(root.right, depth) s = [] dfs1(root, 0) root.val = 0 dfs2(root, 0) return root

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy