Amount of Time for Binary Tree to Be Infected — LeetCode 2385 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#2385
Reading time
5 min

The problem

You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.

Example

Input
root = [1,5,3,null,4,10,6,9,2], start = 3
Output
4
Explanation
The following nodes are infected during:

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 amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        def dfs(node: Optional[TreeNode], fa: Optional[TreeNode]):
            if node is None:
                return
            if fa:
                g[node.val].append(fa.val)
                g[fa.val].append(node.val)
            dfs(node.left, node)
            dfs(node.right, node)

        def dfs2(node: int, fa: int) -> int:
            ans = 0
            for nxt in g[node]:
                if nxt != fa:
                    ans = max(ans, 1 + dfs2(nxt, node))
            return ans

        g = defaultdict(list)
        dfs(root, None)
        return dfs2(start, -1)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the binary tree auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2385. Amount of Time for Binary Tree to Be Infected 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 2385. Amount of Time for Binary Tree to Be Infected?
LeetCode 2385. Amount of Time for Binary Tree to Be Infected is rated Medium on LeetCode.
What is the time complexity of LeetCode 2385. Amount of Time for Binary Tree to Be Infected?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2385. Amount of Time for Binary Tree to Be Infected?
The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
What topics does LeetCode 2385. Amount of Time for Binary Tree to Be Infected cover?
LeetCode 2385. Amount of Time for Binary Tree to Be Infected 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