Problem Description
Given the root of a binary tree with unique node values and a starting value start, the infection begins at the node having value start at minute 0. Each minute, every uninfected node that is adjacent (either as a parent or a child) to an infected node becomes infected. The goal is to determine the total number of minutes required for the infection to spread to every node in the tree.
Key Insights
- Convert the tree structure into an undirected graph. Each node is connected to its left child, right child, and parent.
- Use depth-first search (DFS) to build the graph by traversing the tree.
- Use breadth-first search (BFS) starting from the infected node (start) to compute the number of minutes (levels) needed to infect every node.
- The maximum distance (in terms of levels in BFS) reached from the starting node equals the number of minutes required.
Space and Time Complexity
Time Complexity: O(n) – We traverse each node to build the graph and then each node is processed in the BFS. Space Complexity: O(n) – The graph and the auxiliary data structures (queue and visited set) store information for all nodes.
Solution
We first traverse the binary tree using DFS to build an adjacency list that represents the undirected graph. In this graph, each node's value points to a list of its adjacent node values (its parent and its children). After constructing the graph, we perform a BFS starting from the node corresponding to start. The BFS is performed level by level; each level represents one minute of infection spread. The maximum level encountered gives the number of minutes required to infect the entire tree.