
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.
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val)
3
In JavaScript, this solution models the binary tree as an undirected graph, using adjacency lists, then employs a BFS to simulate infection propagation through these connections.
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.
1class TreeNode:
2 def __init__(self, x):
3 self.val = x
4 self.left = None
5 self.right = None
6
7class Solution:
8 def amountOfTime(self, root: TreeNode, start: int) -> int:
9 def dfs(node, parent):
10 if not node:
11 return 0
12 max_time = 0
13 for child in [node.left, node.right, parent_map.get(node.val)]:
14 if child and child != parent:
15 max_time = max(max_time, dfs(child, node))
16 return max_time + 1
17
18 parent_map = {}
19 start_node = None
20
21 def find_parent_and_start(node, parent):
22 nonlocal start_node
23 if node:
24 if node.val == start:
25 start_node = node
26 parent_map[node.val] = parent
27 find_parent_and_start(node.left, node)
28 find_parent_and_start(node.right, node)
29
30 find_parent_and_start(root, None)
31 return dfs(start_node, None) - 1The Python implementation uses DFS with backtracking methodically, leveraging a dictionary for parent tracking to deduce infection propagation timelines from the starting node.