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, 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
               1
             /   \
            5     3
             \   / \
              4 10  6
             / \
            9   2
Inputroot = [1,5,3,null,4,10,6,9,2], start = 3
Output4
It takes 4 minutes for the infection to spread from node 3 to every node in the tree.
Example 2
        1
Inputroot = [1], start = 1
Output0
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, 10^5].
  • 1 <= Node.val <= 10^5
  • Each node has a unique value.
  • A node with a value of start exists in the tree.

Asked at 12 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate