-
Notifications
You must be signed in to change notification settings - Fork 0
/
Amount of Time for Binary Tree to Be Infected
59 lines (49 loc) Β· 1.55 KB
/
Amount of Time for Binary 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
52
53
54
55
56
57
58
59
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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);
}
};