-
Notifications
You must be signed in to change notification settings - Fork 1
/
Burning Tree.cpp
52 lines (49 loc) · 1.32 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
class Solution {
public:
void solve(int &maxi,Node* root){
if(root==NULL)
return;
maxi=max(maxi,root->data);
solve(maxi,root->left);
solve(maxi,root->right);
}
void constructGraph(Node* root,vector<int>adj[]){
if(root==NULL)
return;
if(root->left){
adj[root->data].push_back(root->left->data);
adj[root->left->data].push_back(root->data);
}
if(root->right){
adj[root->data].push_back(root->right->data);
adj[root->right->data].push_back(root->data);
}
constructGraph(root->left,adj);
constructGraph(root->right,adj);
}
int minTime(Node* root, int target)
{
int maxi=-1;
solve(maxi,root);
vector<int>adj[maxi+1];
constructGraph(root,adj);
queue<pair<int,int>>q;
vector<bool>visit(maxi+1,false);
q.push({0,target});
visit[target]=true;
int ans=0;
while(q.empty()==false){
int dist=q.front().first;
int u=q.front().second;
q.pop();
ans=max(ans,dist);
for(auto v:adj[u]){
if(visit[v]==false){
visit[v]=true;
q.push({dist+1,v});
}
}
}
return ans;
}
};