Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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.
Each minute, a node becomes infected if:
Return the number of minutes needed for the entire tree to be infected.
Example 1:
Input: root = [1,5,3,null,4,10,6,9,2], start = 3 Output: 4 Explanation: The following nodes are infected during: - Minute 0: Node 3 - Minute 1: Nodes 1, 10 and 6 - Minute 2: Node 5 - Minute 3: Node 4 - Minute 4: Nodes 9 and 2 It takes 4 minutes for the whole tree to be infected so we return 4.
Example 2:
Input: root = [1], start = 1 Output: 0 Explanation: At minute 0, the only node in the tree is infected so we return 0.
Constraints:
[1, 105].1 <= Node.val <= 105start exists in the tree.Problem summary: 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. Each minute, a node becomes infected if: The node is currently uninfected. The node is adjacent to an infected node. Return the number of minutes needed for the entire tree to be infected.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Tree
[1,5,3,null,4,10,6,9,2] 3
[1] 1
maximum-depth-of-binary-tree)shortest-path-to-get-food)all-nodes-distance-k-in-binary-tree)count-the-number-of-infection-sequences)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2385: Amount of Time for Binary Tree to Be Infected
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<Integer, List<Integer>> g = new HashMap<>();
public int amountOfTime(TreeNode root, int start) {
dfs(root, null);
return dfs2(start, -1);
}
private void dfs(TreeNode node, TreeNode fa) {
if (node == null) {
return;
}
if (fa != null) {
g.computeIfAbsent(node.val, k -> new ArrayList<>()).add(fa.val);
g.computeIfAbsent(fa.val, k -> new ArrayList<>()).add(node.val);
}
dfs(node.left, node);
dfs(node.right, node);
}
private int dfs2(int node, int fa) {
int ans = 0;
for (int nxt : g.getOrDefault(node, List.of())) {
if (nxt != fa) {
ans = Math.max(ans, 1 + dfs2(nxt, node));
}
}
return ans;
}
}
// Accepted solution for LeetCode #2385: Amount of Time for Binary Tree to Be Infected
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func amountOfTime(root *TreeNode, start int) int {
g := map[int][]int{}
var dfs func(*TreeNode, *TreeNode)
dfs = func(node, fa *TreeNode) {
if node == nil {
return
}
if fa != nil {
g[node.Val] = append(g[node.Val], fa.Val)
g[fa.Val] = append(g[fa.Val], node.Val)
}
dfs(node.Left, node)
dfs(node.Right, node)
}
var dfs2 func(int, int) int
dfs2 = func(node, fa int) (ans int) {
for _, nxt := range g[node] {
if nxt != fa {
ans = max(ans, 1+dfs2(nxt, node))
}
}
return
}
dfs(root, nil)
return dfs2(start, -1)
}
# Accepted solution for LeetCode #2385: Amount of Time for Binary Tree to Be Infected
# 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)
// Accepted solution for LeetCode #2385: Amount of Time for Binary Tree to Be Infected
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2385: Amount of Time for Binary Tree to Be Infected
// /**
// * Definition for a binary tree node.
// * public class TreeNode {
// * int val;
// * TreeNode left;
// * TreeNode right;
// * TreeNode() {}
// * TreeNode(int val) { this.val = val; }
// * TreeNode(int val, TreeNode left, TreeNode right) {
// * this.val = val;
// * this.left = left;
// * this.right = right;
// * }
// * }
// */
// class Solution {
// private Map<Integer, List<Integer>> g = new HashMap<>();
//
// public int amountOfTime(TreeNode root, int start) {
// dfs(root, null);
// return dfs2(start, -1);
// }
//
// private void dfs(TreeNode node, TreeNode fa) {
// if (node == null) {
// return;
// }
// if (fa != null) {
// g.computeIfAbsent(node.val, k -> new ArrayList<>()).add(fa.val);
// g.computeIfAbsent(fa.val, k -> new ArrayList<>()).add(node.val);
// }
// dfs(node.left, node);
// dfs(node.right, node);
// }
//
// private int dfs2(int node, int fa) {
// int ans = 0;
// for (int nxt : g.getOrDefault(node, List.of())) {
// if (nxt != fa) {
// ans = Math.max(ans, 1 + dfs2(nxt, node));
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2385: Amount of Time for Binary Tree to Be Infected
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function amountOfTime(root: TreeNode | null, start: number): number {
const g: Map<number, number[]> = new Map();
const dfs = (node: TreeNode | null, fa: TreeNode | null) => {
if (!node) {
return;
}
if (fa) {
if (!g.has(node.val)) {
g.set(node.val, []);
}
g.get(node.val)!.push(fa.val);
if (!g.has(fa.val)) {
g.set(fa.val, []);
}
g.get(fa.val)!.push(node.val);
}
dfs(node.left, node);
dfs(node.right, node);
};
const dfs2 = (node: number, fa: number): number => {
let ans = 0;
for (const nxt of g.get(node) || []) {
if (nxt !== fa) {
ans = Math.max(ans, 1 + dfs2(nxt, node));
}
}
return ans;
};
dfs(root, null);
return dfs2(start, -1);
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.