Amount of Time for Binary Tree to Be Infected

You are given the root of a binary tree with unique values and an integer `start`. At minute 0 the node with value `start` becomes infected. Each minute, every healthy node that is adjacent to an infected node (its parent or one of its children) becomes infected. Return the number of minutes needed for the whole tree to be infected.

30:00

Amount of Time for Binary Tree to Be Infected
medium
Free written solution
Topics
Companies

You are given the root of a binary tree with unique values and an integer start. At minute 0 the node with value start becomes infected. Each minute, every healthy node that is adjacent to an infected node (its parent or one of its children) becomes infected. Return the number of minutes needed for the whole tree to be infected.

Example 1:
Input: {"root":[1,5,3,null,4,10,6,9,2],"start":3}
Output: 4
Constraints:
  • The number of nodes in the tree is in the range [1,105][1, 10^5].

  • 1≤Node.val≤1051 \leq \text{Node.val} \leq 10^5

  • Each node has a unique value.

  • A node with a value of start exists in the tree.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,5,3,null,4,10,6,9,2],"start":3}

A tree only links parents to children, but infection also spreads upward. First turn the tree into an undirected graph.

minute

-

infected

0 / 8

frontier

0

healthy

infected

just caught it

start

153410692

new infections per minute

nothing infected yet

building parent links

Variables
VariableValue
start3
minutes-1
frontier0
healthy8
DepthFunction Call
Stack empty
0/15