Given the root of a binary tree and a target node, find the minimum time required to burn the entire tree if the target node is set on fire. In one second, the fire spreads from a node to its left child, right child, and parent. Note: The tree contains unique values.
[Approach- 1] Using Queue - O(n) Time and O(n) Space
The fire spreads to neighboring nodes first, then to their neighbors, and so on. In other words, the fire spreads level by level. To simulate this, we use BFS to traverse the tree in all directions, towards children and the parent. Since we need to move upwards, we first keep track of the parent of each node. Then, starting from the target node, we perform a level-order traversal. The number of levels traversed during this process gives the minimum time required to burn the entire tree.
In JavaScript there is no any built in queue so we are using custom queue.
Output
3
[Alternate Approach] Using Recursion - O(n) Time and O(h) Space
The fire spreads level by level from the target node. The total time to burn the entire tree is determined by the farthest node reached by the fire. In other words, the minimum time to burn the whole tree is simply the distance from the target node to the farthest node. This reduces the problem to finding the farthest node from the target.
The idea is to find the parent of each node and recursively explore all paths from the target node to find the farthest node. The distance to this node gives the minimum time required to burn the entire tree.