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.
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:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 105
Each node has a unique value.
A node with a value of start exists in the tree.
Solutions
Solution 1: Two DFS
Thinking
Infection travels along tree edges; the time is the eccentricity of \(start\). Up to \(10^5\) nodes, so parent links must be explicit.
The first DFS builds an undirected adjacency list; the second DFS from \(start\) returns the farthest depth. Both are linear.
First, we build a graph through one DFS, and get an adjacency list \(g\), where \(g[node]\) represents all nodes connected to the node \(node\).
Then, we use \(start\) as the starting point, and search the entire tree through DFS to find the farthest distance, which is the answer.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary tree.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcamountOfTime(root*TreeNode,startint)int{g:=map[int][]int{}vardfsfunc(*TreeNode,*TreeNode)dfs=func(node,fa*TreeNode){ifnode==nil{return}iffa!=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)}vardfs2func(int,int)intdfs2=func(node,faint)(ansint){for_,nxt:=rangeg[node]{ifnxt!=fa{ans=max(ans,1+dfs2(nxt,node))}}return}dfs(root,nil)returndfs2(start,-1)}
Infection spreads along parent and child edges, so the minutes needed are the farthest distance from \(start\). Recording those edges and then returning a depth is correct on a short tree.
The tree can contain \(10^5\) nodes. A left chain makes both walks recurse once per node, which exceeds the call stack.
Each walk only needs the current node and its parent, and a node's depth is one plus the maximum depth of its other neighbors. Those values can sit beside an explicit stack.
The first stack records every parent edge in an undirected adjacency list, using the distinct node values as keys. The second stack enters a node, pushes its neighbors, and on exit writes one plus the maximum neighbor depth. The depth stored for \(start\) is the answer.
We traverse the binary tree with an explicit stack and record each parent-child edge in an undirected adjacency list \(g\). Node values are distinct, so they are the graph keys.
A second explicit stack then walks outward from \(start\). On entry it pushes an exit marker and every neighbor except the parent; on exit the depth is one plus the maximum depth of those neighbors. The depth stored for \(start\) is the answer.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary tree.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcamountOfTime(root*TreeNode,startint)int{g:=map[int][]int{}typeframestruct{node,fa*TreeNode}stk:=[]frame{{root,nil}}forlen(stk)>0{cur:=stk[len(stk)-1]stk=stk[:len(stk)-1]node,fa:=cur.node,cur.faifnode==nil{continue}iffa!=nil{g[node.Val]=append(g[node.Val],fa.Val)g[fa.Val]=append(g[fa.Val],node.Val)}stk=append(stk,frame{node.Right,node},frame{node.Left,node})}dist:=map[int]int{}typestepstruct{node,fa,stateint}walk:=[]step{{start,-1,0}}forlen(walk)>0{cur:=walk[len(walk)-1]walk=walk[:len(walk)-1]node,fa,state:=cur.node,cur.fa,cur.statenxts:=g[node]ifstate==0{walk=append(walk,step{node,fa,1})fori:=len(nxts)-1;i>=0;i--{ifnxt:=nxts[i];nxt!=fa{walk=append(walk,step{nxt,node,0})}}continue}best:=0for_,nxt:=rangenxts{ifnxt!=fa{best=max(best,1+dist[nxt])}}dist[node]=best}returndist[start]}