-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBurning Tree
47 lines (39 loc) Β· 1.32 KB
/
Burning Tree
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
class Solution {
private:
unordered_map<Node*, Node*> parent;
Node* targetNode = nullptr;
void findTarget(Node* node, int target, Node* par = nullptr) {
if (!node) return;
parent[node] = par;
if (node->data == target) targetNode = node;
findTarget(node->left, target, node);
findTarget(node->right, target, node);
}
public:
int minTime(Node* root, int target) {
findTarget(root, target);
if (!targetNode) return 0;
queue<Node*> q;
unordered_set<Node*> visited;
q.push(targetNode);
visited.insert(targetNode);
int time = 0;
while (!q.empty()) {
int size = q.size();
bool burned = false;
for (int i = 0; i < size; i++) {
Node* node = q.front(); q.pop();
vector<Node*> neighbors = {node->left, node->right, parent[node]};
for (Node* nei : neighbors) {
if (nei && visited.find(nei) == visited.end()) {
q.push(nei);
visited.insert(nei);
burned = true;
}
}
}
if (burned) time++;
}
return time;
}
};