Amount of Time for Binary Tree to Be Infected LeetCode Solution

Problem – Amount of Time for Binary Tree to Be Infected

You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.

Each minute, a node becomes infected if:

  • The node is currently uninfected.
  • The node is adjacent to an infected node.

Return the number of minutes needed for the entire tree to be infected.

Example 1:

Input: root = [1,5,3,null,4,10,6,9,2], start = 3
Output: 4
Explanation: The following nodes are infected during:
- Minute 0: Node 3
- Minute 1: Nodes 1, 10 and 6
- Minute 2: Node 5
- Minute 3: Node 4
- Minute 4: Nodes 9 and 2
It takes 4 minutes for the whole tree to be infected so we return 4.

Example 2:

Input: root = [1], start = 1
Output: 0
Explanation: At minute 0, the only node in the tree is infected so we return 0.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 105
  • Each node has a unique value.
  • A node with a value of start exists in the tree.

Amount of Time for Binary Tree to Be Infected LeetCode Solution in C++

unordered_map<int,list<int>> v;  //adjacency list

//create undirected graph for every parent-child  -> BFS
void createGraph(TreeNode* root){
    queue<pair<TreeNode*,int>> q;
    q.push({root,-1});
    while(q.size()){
        auto [node,parent]= q.front(); q.pop();
        if(parent!=-1){
            v[parent].push_front(node->val);
            v[node->val].push_front(parent);
        }
        if(node->left)  q.push({node->left,node->val});
        if(node->right) q.push({node->right,node->val});
    }   
}

int amountOfTime(TreeNode* root, int start) {
    //create graph of given tree
    createGraph(root);

    //start bfs
    queue<int> q;
    unordered_map<int,bool> seen;
    q.push(start);
    seen[start]=true;
    int time=0;
    for(;q.size();time++){
        int n= q.size();
        while(n--){
            auto node= q.front();  q.pop();
            for(auto i:v[node]){
                if(!seen[i]){
                    q.push(i);
                    seen[i]=true;
                }
            }
        }
    }
    return time-1;
}

Amount of Time for Binary Tree to Be Infected LeetCode Solution in Java

class Solution {
    public int amountOfTime(TreeNode root, int start) {
        HashMap<TreeNode, TreeNode> mpp=new HashMap<>();
        TreeNode target=bfsToMapParents(root,mpp,start);
        
       return findMaxDistance(mpp, target);
    }
    private static int findMaxDistance(HashMap<TreeNode, TreeNode> mpp, TreeNode target) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(target);
        HashMap<TreeNode,Integer> vis = new HashMap<>();
        vis.put(target, 1);
        int maxi = 0;
        
        while(!q.isEmpty()) {
            int sz = q.size();
            int fl = 0;
            
            for(int i = 0;i<sz;i++) {
                TreeNode node = q.poll();
                if(node.left != null && vis.get(node.left) == null) {
                    fl = 1;
                    vis.put(node.left, 1);
                    q.offer(node.left);
                }
                if(node.right != null && vis.get(node.right) == null) {
                    fl = 1;
                    vis.put(node.right, 1);
                    q.offer(node.right);
                }

                if(mpp.get(node) != null && vis.get(mpp.get(node)) == null) {
                    fl = 1;
                    vis.put(mpp.get(node), 1);
                    q.offer(mpp.get(node));
                }
            }
            if(fl == 1) maxi++;
        }
        return maxi;
    }
     TreeNode bfsToMapParents(TreeNode root,HashMap<TreeNode, TreeNode> mpp, int start) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        TreeNode res = new TreeNode(-1);
        while(!q.isEmpty()) {
            TreeNode node = q.poll();
            if(node.val == start) res = node;
            if(node.left != null) {
                mpp.put(node.left, node);
                q.offer(node.left);
            }
            if(node.right != null) {
                mpp.put(node.right, node);
                q.offer(node.right);
            }
        }
        return res;
    }
}

Amount of Time for Binary Tree to Be Infected LeetCode Solution in Python

class Solution:
    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        graph = defaultdict(list)
        
        def build_graph(parent, node):
            if not node: return 
            
            if parent:
                graph[parent.val].append(node)
                graph[node.val].append(parent)
            
            build_graph(node, node.left)
            build_graph(node, node.right)
        
        build_graph(None, root)
        
        vis = set()
        max_infection = 0
        queue = deque([(start, 0)])
        vis.add(start)
        
        while queue:
            node_val, time = queue.popleft()
            max_infection = max(max_infection, time)
            
            for nei in graph[node_val]:
                if nei.val not in vis:
                    vis.add(nei.val)
                    queue.append((nei.val, time + 1))
        
        return max_infection
Amount of Time for Binary Tree to Be Infected LeetCode Solution Review:

In our experience, we suggest you solve this Amount of Time for Binary Tree to Be Infected LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Amount of Time for Binary Tree to Be Infected LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Amount of Time for Binary Tree to Be Infected LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *