-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2385.cpp
More file actions
53 lines (49 loc) · 1.47 KB
/
Copy path2385.cpp
File metadata and controls
53 lines (49 loc) · 1.47 KB
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
class Solution {
public:
int amountOfTime(TreeNode *root, int start) const {
unordered_map<TreeNode *, TreeNode *> parent;
queue<TreeNode *> q;
TreeNode *infected;
q.push(root);
while (!q.empty()) {
TreeNode *root = q.front();
q.pop();
if (root->val == start) {
infected = root;
break;
}
if (root->left) {
parent.insert({root->left, root});
q.push(root->left);
}
if (root->right) {
parent.insert({root->right, root});
q.push(root->right);
}
}
int depth = -1;
q = queue<TreeNode *>();
q.push(infected);
while (!q.empty()) {
depth++;
for (int k = q.size(); k > 0; k--) {
TreeNode *root = q.front();
q.pop();
if (parent.count(root)) {
TreeNode *prnt = parent[root];
(prnt->left == root ? prnt->left : prnt->right) = nullptr;
q.push(parent[root]);
}
if (root->left) {
q.push(root->left);
parent.erase(root->left);
}
if (root->right) {
q.push(root->right);
parent.erase(root->right);
}
}
}
return depth;
}
};