Cousins in Binary Tree II — LeetCode 2641 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#2641
Reading time
6 min

The problem

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.

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.

Python solution

Python
# 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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2641. Cousins in Binary Tree II is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2641. Cousins in Binary Tree II?
LeetCode 2641. Cousins in Binary Tree II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2641. Cousins in Binary Tree II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2641. Cousins in Binary Tree II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2641. Cousins in Binary Tree II cover?
LeetCode 2641. Cousins in Binary Tree II is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview