Minimum time taken to burn the BT from a given Node

Pattern: Level order BFS

medium

Fire spreads each second from a burning node to its children and its parent. Record parents, then BFS from the start node one ring per second; the number of rounds until no new node catches fire is the answer.

The problem

A fire starts at the node with value start at time 0. Each second it spreads from every burning node to its children and its parent. Return the time when the whole tree is burning. Values are different. The example gives 3. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Which nodes catch fire after one second?
  • Is this like the distance-k problem?
  • What is the answer in terms of distances?

Hints

    Brute force, and why it fails

    Compute the distance from the start to every node separately: O(n²).

    The key insight

    With parent links, one BFS from the start gives every node's distance, and the last ring reached is the answer.

    Dry run

    burning1
    time0

    Tree [1, 2, 3, 4, null, 5, 6, null, 7], start 1. Second 0: {1}.

    Step 1 of 3

    The plan

    record parents; find the start node
    ring = [start]; time = -1
    while ring: ring = unvisited neighbours of ring; time += 1
    return time
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One BFS.

    Edge cases

    • One node: 0.
    • Start at a leaf.
    • Start at the root: the height minus 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int timeToBurnTree(TreeNode root, int start) {
            Map<TreeNode, TreeNode> parent = new HashMap<>();
            link(root, null, parent);
            TreeNode fire = TreeNode.find(root, start);
            Set<TreeNode> burnt = new HashSet<>();
            Queue<TreeNode> q = new ArrayDeque<>();
            q.add(fire);
            burnt.add(fire);
            int time = -1;
            while (!q.isEmpty()) {                  // each round, fire spreads to every neighbour
                int size = q.size();
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    for (TreeNode next : new TreeNode[]{node.left, node.right, parent.get(node)}) {
                        if (next != null && burnt.add(next)) q.add(next);
                    }
                }
                time++;
            }
            return time;
        }
    
        private void link(TreeNode node, TreeNode up, Map<TreeNode, TreeNode> parent) {
            if (node == null) return;
            parent.put(node, up);
            link(node.left, node, parent);
            link(node.right, node, parent);
        }
    }

    C++

    class Solution {
    public:
        int timeToBurnTree(TreeNode* root, int start) {
            unordered_map<TreeNode*, TreeNode*> parent;
            link(root, NULL, parent);
            TreeNode* fire = findNode(root, start);
            unordered_set<TreeNode*> burnt;
            queue<TreeNode*> q;
            q.push(fire);
            burnt.insert(fire);
            int time = -1;
            while (!q.empty()) {                    // each round, fire spreads to every neighbour
                int size = static_cast<int>(q.size());
                for (int i = 0; i < size; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    TreeNode* nexts[3] = {node->left, node->right, parent[node]};
                    for (TreeNode* next : nexts) {
                        if (next != NULL && burnt.insert(next).second) q.push(next);
                    }
                }
                time++;
            }
            return time;
        }
    
        void link(TreeNode* node, TreeNode* up, unordered_map<TreeNode*, TreeNode*>& parent) {
            if (node == NULL) return;
            parent[node] = up;
            link(node->left, node, parent);
            link(node->right, node, parent);
        }
    };

    Python

    class Solution:
        def timeToBurnTree(self, root, start: int) -> int:
            parent, fire = {}, None
    
            def link(node, up):
                nonlocal fire
                if node:
                    parent[node] = up
                    if node.val == start and fire is None:
                        fire = node
                    link(node.left, node)
                    link(node.right, node)
    
            link(root, None)
            burnt, ring, time = {fire}, [fire], -1
            while ring:                             # each round, fire spreads to every neighbour
                nxt = []
                for node in ring:
                    for other in (node.left, node.right, parent[node]):
                        if other and other not in burnt:
                            burnt.add(other)
                            nxt.append(other)
                ring, time = nxt, time + 1
            return time

    Common mistakes

    • Counting the starting second as 1.
    • Ignoring the parent direction.

    Similar problems