-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_BurningTree.cpp
116 lines (108 loc) · 3.07 KB
/
GFG_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
https://practice.geeksforgeeks.org/problems/burning-tree/1
Burning Tree
*/
class Solution {
public:
/*
int minTime(Node* root, int target)
{
unordered_map<Node*, Node*> um;
Node* tarnode = map_child_par(root, um, target);
int time = func(um, tarnode);
return time;
}
Node* map_child_par(Node* root, unordered_map<Node*, Node*> &um, int tg)
{
queue<Node*> q; q.push(root);
Node* tarnodeptr;
while(!q.empty())
{
Node* cur = q.front(); q.pop();
if(cur->data == tg) tarnodeptr = cur;
if(cur->left)
{
um[cur->left] = cur;
q.push(cur->left);
}
if(cur->right)
{
um[cur->right] =cur;
q.push(cur->right);
}
}
return tarnodeptr;
}
int func(unordered_map<Node*, Node*> &par, Node* tg)
{
int time=0;
unordered_map<Node* , bool> visit;
queue<Node*> q; q.push(tg);
visit[tg] = true;
while(!q.empty())
{
int sz = q.size();
bool check = false;
while(sz--)
{
Node* cur = q.front(); q.pop();
if(cur->left and !visit[cur->left])
{
check = true;
visit[cur->left] = true;
q.push(cur->left);
}
if(cur->right and !visit[cur->right])
{
check = true;
visit[cur->right] = true;
q.push(cur->right);
}
if(par[cur] and !visit[par[cur]])
{
check = true;
visit[par[cur]] = true;
q.push(par[cur]);
}
}
if(check) time++;
}
return time;
}
*/
// /*
int time=0;
int tg=0;
int minTime(Node* root, int target)
{
tg = target;
burnDfs(root);
return time;
}
pair<int, bool> burnDfs (Node* root){
if(!root) return {0, false};
pair<int, bool> left, right;
if(root->left) left = burnDfs(root->left);
else left = {0, false};
if(root->right) right = burnDfs(root->right);
else right = {0, false};
// myprint({root->data, left.first, right.first, (left.second), (right.second), time});
if(root->data == tg){
time = max(left.first, right.first);
return {1, true};
}
if(left.second)
{
time = max(time, right.first + left.first);
return {left.first + 1, true};
}
if(right.second)
{
time = max(time, right.first + left.first);
return {right.first + 1, true};
}
return { 1 + max(left.first, right.first), false};
}
void myprint(vector<int> vec) { for(int x: vec) cout<<x<<" "; cout<<endl; }
// */
};