




Sponsored
Sponsored
Approach 1: Breadth-First Search (BFS)
This approach involves simulating the infection spread using BFS, starting from the infected node. Each level of the BFS traversal represents one minute of infection spreading.
The steps are as follows:
Time Complexity: O(N) where N is the number of nodes; we visit each node once.
Space Complexity: O(N) to store the adjacency list and manage the queue.
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdbool.h>
4
5#define MAX_NODES
This C solution creates a graph-like structure from the binary tree and performs a breadth-first search from the start node to determine the infection spread time.
Approach 2: Depth-First Search with Backtracking
In this method, we perform a depth-first search (DFS) to calculate the maximum distance (time) required to infect every node from the start node, utilizing backtracking to manage node revisits.
Steps include:
Time Complexity: O(N)
Space Complexity: O(N) for the recursion stack if the tree is unbalanced.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5    public int val;
6    public TreeNode left;
7    public TreeNode right;
8    public TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12    private TreeNode targetNode;
13    private Dictionary<int, TreeNode> parents = new Dictionary<int, TreeNode>();
14
15    public int AmountOfTime(TreeNode root, int start) {
16        FindStartAndParents(root, null, start);
17        return DFS(targetNode, null) - 1;
18    }
19
20    private void FindStartAndParents(TreeNode node, TreeNode parent, int start) {
21        if (node == null) return;
22        if (node.val == start) targetNode = node;
23        if (parent != null) parents[node.val] = parent;
24        FindStartAndParents(node.left, node, start);
25        FindStartAndParents(node.right, node, start);
26    }
27
28    private int DFS(TreeNode node, TreeNode parent) {
29        if (node == null) return 0;
30        int left = node.left != parent ? DFS(node.left, node) : 0;
31        int right = node.right != parent ? DFS(node.right, node) : 0;
32        int par = parents.ContainsKey(node.val) && parents[node.val] != parent ? DFS(parents[node.val], node) : 0;
33        return Math.Max(left, Math.Max(right, par)) + 1;
34    }
35}This C# approach effectively utilizes recursive backtracking in DFS to derive the maximum minutes until the complete infection spread, with a map to assist node-to-parent relevancy.