-
Notifications
You must be signed in to change notification settings - Fork 0
/
infectedBinaryTree.txt
54 lines (45 loc) · 1.58 KB
/
infectedBinaryTree.txt
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
52
53
54
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.
class Solution {
public:
unordered_map<int, vector<int>> graph;
int amountOfTime(TreeNode* root, int start) {
constructGraph(root);
queue<int> q;
q.push(start);
unordered_set<int> visited;
int minutesPassed = -1;
while (!q.empty()) {
++minutesPassed;
for (int levelSize = q.size(); levelSize > 0; --levelSize) {
int currentNode = q.front();
q.pop();
visited.insert(currentNode);
for (int adjacentNode : graph[currentNode]) {
if (!visited.count(adjacentNode)) {
q.push(adjacentNode);
}
}
}
}
return minutesPassed;
}
void constructGraph(TreeNode* root) {
if (!root) return;
if (root->left) {
graph[root->val].push_back(root->left->val);
graph[root->left->val].push_back(root->val);
}
if (root->right) {
graph[root->val].push_back(root->right->val);
graph[root->right->val].push_back(root->val);
}
constructGraph(root->left);
constructGraph(root->right);
}
};