-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAmountofTimeforBinaryTreetoBeInfected_2385.cpp
82 lines (63 loc) · 2.22 KB
/
AmountofTimeforBinaryTreetoBeInfected_2385.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 2385. Amount of Time for Binary Tree to Be Infected
~ Link : https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/
*/
/**
* 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<TreeNode*, TreeNode*> parentMap;
TreeNode *startNode;
void getParent(TreeNode *root, TreeNode *parent, int start) {
if (!root)
return;
if (root -> val == start)
startNode = root;
parentMap[root] = parent;
getParent(root -> left, root, start);
getParent(root -> right, root, start);
}
int amountOfTime(TreeNode* root, int start) {
getParent(root, NULL, start);
queue<TreeNode*> todo;
todo.push(startNode);
unordered_map<TreeNode*, bool> visited;
visited[startNode] = true;
int minutesElapsed = 0;
while (!todo.empty()) {
int levelSize = todo.size();
while (levelSize--) {
TreeNode *curr = todo.front();
todo.pop();
TreeNode *parentNode = parentMap[curr];
if (parentNode && !visited[parentNode]) {
todo.push(parentNode);
visited[parentNode] = true;
}
if (curr -> left && !visited[curr -> left]) {
todo.push(curr -> left);
visited[curr -> left] = true;
}
if (curr -> right && !visited[curr -> right]) {
todo.push(curr -> right);
visited[curr -> right] = true;
}
}
if (todo.size())
++minutesElapsed;
}
return minutesElapsed;
}
};
// Time Complexity - O(n)
// Auxiliary Space - O(n)