Approach
Breadth-first search
For Amount of Time for Binary Tree to Be Infected, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 49 lines of Java from the credited upstream file 2385.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int amountOfTime(TreeNode root, int start) {3 int ans = -1;4 Map<Integer, List<Integer>> graph = getGraph(root);5 Queue<Integer> q = new ArrayDeque<>(List.of(start));6 Set<Integer> seen = new HashSet<>(Arrays.asList(start));7 8 for (; !q.isEmpty(); ++ans) {9 for (int sz = q.size(); sz > 0; --sz) {10 final int u = q.poll();11 if (!graph.containsKey(u))12 continue;13 for (final int v : graph.get(u)) {14 if (seen.contains(v))15 continue;16 q.offer(v);17 seen.add(v);18 }19 }20 }21 22 return ans;23 }24 25 private Map<Integer, List<Integer>> getGraph(TreeNode root) {26 Map<Integer, List<Integer>> graph = new HashMap<>();27 28 Queue<Pair<TreeNode, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(root, -1)));29 30 while (!q.isEmpty()) {31 Pair<TreeNode, Integer> pair = q.poll();32 TreeNode node = pair.getKey();33 final int parent = pair.getValue();34 if (parent != -1) {35 graph.putIfAbsent(parent, new ArrayList<>());36 graph.putIfAbsent(node.val, new ArrayList<>());37 graph.get(parent).add(node.val);38 graph.get(node.val).add(parent);39 }40 if (node.left != null)41 q.add(new Pair<>(node.left, node.val));42 if (node.right != null)43 q.add(new Pair<>(node.right, node.val));44 }45 46 return graph;47 }48}49