-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathBurningTree.cpp
79 lines (65 loc) · 2.24 KB
/
BurningTree.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
// https://practice.geeksforgeeks.org/problems/burning-tree/1
class Solution {
public:
int minTime(Node* root, int target)
{
// Your code goes here
if(root==NULL)
return 0;
map<Node*, Node*> childToParent;
map<Node*, bool> visited;
queue<Node*> q;
Node* targetNode= NULL;
q.push(root);
childToParent[root]= NULL;
// To store childToParent mapping and get the targetNode
while(!q.empty()){
int size= q.size();
for(int i=0; i<size; i++){
Node* tempNode= q.front();
q.pop();
visited[tempNode]= false;
if(tempNode->data==target)
targetNode= tempNode;
if(tempNode->left){
q.push(tempNode->left);
childToParent[tempNode->left]= tempNode;
}
if(tempNode->right){
q.push(tempNode->right);
childToParent[tempNode->right]= tempNode;
}
}
}
int count= 0;
q.push(targetNode);
visited[targetNode]= true;
bool inserted= false;
while(!q.empty()){
inserted= false;
int size= q.size();
for(int i=0; i<size; i++){
Node* tempNode= q.front();
q.pop();
if(tempNode->left && !visited[tempNode->left]){
q.push(tempNode->left);
visited[tempNode->left]= true;
inserted= true;
}
if(tempNode->right && !visited[tempNode->right]){
q.push(tempNode->right);
visited[tempNode->right]= true;
inserted= true;
}
if(childToParent[tempNode] && !visited[childToParent[tempNode]]){
q.push(childToParent[tempNode]);
visited[childToParent[tempNode]]= true;
inserted= true;
}
}
if(inserted)
count++;
}
return count;
}
};