-
Notifications
You must be signed in to change notification settings - Fork 0
/
Burning Tree.cpp
80 lines (67 loc) · 2.03 KB
/
Burning Tree.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
class Solution {
public:
Node* createParentMapping(Node* root,int target,map<Node* , Node*> &nodeToParent){
Node* res = NULL;
queue<Node*> q;
q.push(root);
nodeToParent[root] = NULL;
while(!q.empty()){
Node* front = q.front();
q.pop();
if(front-> data == target){
res = front;
}
if(front-> left){
nodeToParent[front -> left] = front;
q.push(front-> left);
}
if(front-> right){
nodeToParent[front -> right] = front;
q.push(front-> right);
}
}
return res;
}
int burnTree(Node* root , map<Node* , Node*> &nodeToParent){
map<Node*,bool> visited;
queue<Node*> q;
q.push(root);
visited[root] = true;
int ans=0;
while(!q.empty()){
bool flag = 0;
int size = q.size();
for(int i=0;i<size;i++){
Node* front = q.front();
q.pop();
if(front->left && !visited[front->left]){
flag =1;
q.push(front->left);
visited[front->left] = 1;
}
if(front->right && !visited[front->right]){
flag = 1;
q.push(front->right);
visited[front->right] = 1;
}
if(nodeToParent[front] && !visited[nodeToParent[front]]){
flag = 1;
q.push(nodeToParent[front]);
visited[nodeToParent[front]] = 1;
}
}
if(flag==1){
ans++;
}
}
return ans;
}
int minTime(Node* root, int target)
{
// Your code goes here
map<Node* , Node*> nodeToParent;
Node* targetNode = createParentMapping(root,target,nodeToParent);
int result= burnTree(targetNode,nodeToParent);
return result;
}
};