Amount of Time for Binary Tree to Be Infected

Medium

Description

Given a binary tree and a start node, infection spreads to adjacent nodes each minute. Return minutes until all nodes infected.

Examples

Input:root = [1,5,3,null,4,10,6,9,2], start = 3
Output:4
Explanation:

4 minutes to infect all.

Input:root = [1,2,3,4,5], start = 1
Output:2
Explanation:

Starting from root node 1, infection spreads to children 2 and 3 in minute 1, then to nodes 4 and 5 in minute 2. Total time is 2 minutes.

Input:root = [7,8,9,null,null,10,11,null,12], start = 12
Output:4
Explanation:

Starting from leaf node 12, infection spreads up to parent 10 (minute 1), then to 9 and 11 (minute 2), then to 7 (minute 3), and finally to 8 (minute 4). Takes 4 minutes total.

Constraints

  • 1 ≤ nodes ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!