oneby7

Binary Trees Breadth first: level by level

371. Amount of Time for Binary Tree to Be Infected

Medium

You are given root, the root node of a binary tree, and an integer start. At minute 0, the node whose value is start becomes infected. Every minute after that, each infected node infects its neighbours that are not infected yet. The neighbours of a node are its parent and its children.

Return the number of minutes it takes for every node in the tree to be infected.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out. The values in the tree are distinct, so start names exactly one node.

Example 1

7389645-211

Input: root = [4, 7, -2, null, 9, 5, 11, 3, 6, null, null, null, null, null, 8] start = 9

Output: 4

Explanation: At minute 1, 9 infects its children 3 and 6 and its parent 7. At minute 2, 8 and 4 are infected, then −2 at minute 3. The last nodes, 5 and 11, are infected at minute 4.

Example 2

8

Input: root = [8], start = 8

Output: 0

Explanation: The only node is infected at minute 0, so no time passes.

Example 3

−10⁹01210⁹

Input: root = [0, -1000000000, 1000000000, null, null, 12] start = 0

Output: 2

Explanation: The infection starts at the root, so it only moves down. 12 is two levels below the root and is infected last.

Check your understanding

Work out the answer for this input before you write any code.

root = [1, 2, 3, 4, 5, null, null, 6, null, null, 7, null, null, null, 8] start = 6

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • All the values in the tree are distinct.
  • start is a value in the tree.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.