MediumNo. 2385
Amount of Time for Binary Tree to Be Infected — LeetCode 2385 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree
- Reading time
- 5 min
- Source
- leetcode.com
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
# 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
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the number of nodes in the binary tree
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
| No. | Problem | Difficulty |
|---|---|---|
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
| 1261 | Find Elements in a Contaminated Binary Tree | Medium |
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.