2385. 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
class Solution { unordered_map<int, vector<int>> adj; unordered_set<int> vis; void dfs(TreeNode* node) { if(!node) return; int v = node->val; if(node->left) { adj[v].push_back(node->left->val); adj[node->left->val].push_back(v); dfs(node->left); } if(node->right) { adj[v].push_back(node->right->val); adj[node->right->val].push_back(v); dfs(node->right); } } public: int amountOfTime(TreeNode* root, int start) { dfs(root); queue<int> q; q.push(start); vis.insert(start); int res = 0; while(!q.empty()) { int sz = q.size(); while(sz--) { int u = q.front(); q.pop(); for(auto& v : adj[u]) { if(!vis.count(v)) { vis.insert(v); q.push(v); } } } res++; } return res - 1; } };
|