-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBurning-Tree.cpp
113 lines (104 loc) · 2.88 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
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
// https://practice.geeksforgeeks.org/problems/burning-tree/1
// BFS based approach:
/*
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
*/
class Solution {
public:
int minTime(Node* root, int target)
{
// we need to store the parent
unordered_map<Node*, Node*> umap;
queue<Node*> q;
q.push(root);
Node* start = NULL;
while(!q.empty()){
Node* front = q.front(); q.pop();
if(front->data == target) start = front;
Node* left = front->left;
Node* right = front->right;
if(left){
umap[left] = front;
q.push(left);
}
if(right){
umap[right] = front;
q.push(right);
}
}
// now traverse from the target until the tree becomes empty
q.push(start);
int time = 0;
while(!q.empty()){
int sz = q.size();
while(sz--){
Node* front = q.front(); q.pop();
if(front->data == 696969) continue;
front->data = 696969;
Node* left = front->left;
Node* right = front->right;
Node* parent = umap[front];
if(left && left->data!=696969) q.push(left);
if(right && right->data!=696969) q.push(right);
if(parent && parent->data!=696969) q.push(parent);
}
time++;
}
return time-1;
}
};
// DFS based approach:
/*
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
*/
class Solution {
public:
int solve(Node* start, unordered_map<Node*, Node*>& umap){
if(start == NULL || start->data==696969) return 0;
start->data = 696969;
int leftChild = solve(start->left, umap);
int rightChild = solve(start->right, umap);
int parent = solve(umap[start], umap);
return 1 + max({leftChild, rightChild, parent});
}
int minTime(Node* root, int target)
{
// we need to store the parent
unordered_map<Node*, Node*> umap;
queue<Node*> q;
q.push(root);
Node* start = NULL;
while(!q.empty()){
Node* front = q.front(); q.pop();
if(front->data == target) start = front;
Node* left = front->left;
Node* right = front->right;
if(left){
umap[left] = front;
q.push(left);
}
if(right){
umap[right] = front;
q.push(right);
}
}
// now traverse from the target until the tree becomes empty
return solve(start, umap)-1;
}
};