Problem 743
Minimum Time to Burn a Binary Tree
Hard · 30 pts · Tree, Breadth-First Search
Problem
A fire starts at the node with value START in a binary tree with distinct values. Every second, the fire spreads from each burning node to all of its neighbours: its left child, right child and parent. Find the number of seconds until the whole tree is burning. Record every node's parent with one traversal, then run a breadth-first search from the start node over the three kinds of edges; the answer is the number of BFS levels after the first.
Input
The first line contains START. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children. All values are distinct.
Output
Print the number of seconds needed to burn the whole tree.
Constraints
1 <= number of nodes <= 10000; values are distinct; START is in the tree
Example input
1 9 1 2 3 4 null 5 6 null 7
Example output
3
Explanation
In the tree 1 2 3 4 null 5 6 null 7 starting at 1: after 1 second 2 and 3 burn, after 2 seconds 4, 5 and 6, and after 3 seconds 7. So the answer is 3.