-
Notifications
You must be signed in to change notification settings - Fork 0
/
Burn_the_tree
73 lines (72 loc) · 2.08 KB
/
Burn_the_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
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
Node* findTargetNodeAndGetParent(Node* root,int target,unordered_map<Node*,Node*>& parent)
{
queue<Node*>q;
q.push(root);
Node* tar=NULL;
bool check=0;
while(!q.empty())
{
int size=q.size();
for(int i=0;i<size;i++)
{
Node* temp=q.front();
q.pop();
if(temp->data==target && check==0)
{
tar=temp;
check=1;
}
if(temp->left != NULL)
{
parent[temp->left]=temp;
q.push(temp->left);
}
if(temp->right != NULL)
{
parent[temp->right]=temp;
q.push(temp->right);
}
}
}
return tar;
}
int minTime(Node* root, int target)
{
unordered_map<Node*,Node*> parent;
Node* tar = findTargetNodeAndGetParent(root,target,parent);
if(tar==NULL)
return 0;
unordered_set<Node*>visited;
int seconds=0;
queue<Node*>q;
q.push(tar);
while(!q.empty())
{
int find=0;
int size=q.size();
for(int i=0;i<size;i++)
{
Node* temp=q.front();
q.pop();
visited.insert(temp);
if((parent[temp]) && (visited.find(parent[temp]) == visited.end()))
{
q.push(parent[temp]);
find=1;
}
if((temp->left != NULL) && (visited.find(temp->left)==visited.end()))
{
q.push(temp->left);
find=1;
}
if((temp->right != NULL) && (visited.find(temp->right)==visited.end()))
{
q.push(temp->right);
find=1;
}
}
if(find)
seconds++;
}
return seconds;
}