-
Notifications
You must be signed in to change notification settings - Fork 0
/
burn_a_tree.cpp
68 lines (55 loc) · 1.45 KB
/
burn_a_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
#include <bits/stdc++.h>
using namespace std;
#define tn TreeNode*
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
unordered_map<tn, bool> m;
unordered_map<tn, tn> par;
tn bn = NULL;
void find(tn a, int b){
queue<tn> q;
q.push(a);
while(!q.empty()){
int sz = q.size();
while(sz--){
tn t = q.front(); q.pop();
//m[t] = false;
if(t->val == b){
tn x = t;
//cout << "found" << "\n";
bn = x;
//cout << bn->val << "\n";
}
if(t->left != NULL) q.push(t->left), par[t->left] = t;
if(t->right != NULL) q.push(t->right), par[t->right] = t;
}
}
return;
}
int ans = 0;
void burn(tn bn, int t){
if(bn == NULL) return;
//if(m.find(bn) != m.end() && m[bn] == true) return;
ans = max(ans, t);
m[bn] = true;
if(par.find(bn) != par.end() && m[par[bn]] == false) burn(par[bn], t+1);
if(bn->left && m[bn->left] == false) burn(bn->left, t+1);
if(bn->right && m[bn->right] == false) burn(bn->right, t+1);
return;
}
int solve(TreeNode* a, int b) {
bn = NULL;
find(a, b);
ans = 0;
if(bn == NULL) return INT_MAX;
//else cout << bn->val << "\n";
burn(bn, 0);
cout << std::flush;
m.clear(); par.clear();
bn = NULL;
return ans;
}