-
Notifications
You must be signed in to change notification settings - Fork 0
/
Burning_Tree.cpp
55 lines (54 loc) · 1.26 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
/*
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
*/
class Solution {
public:
unordered_map<Node*,Node*> par;
unordered_map<Node*,bool> vis;
Node *tar =nullptr;
int minTime(Node* root, int target)
{
dfs1(root,target);
return dfs2(tar)-1;
}
void dfs1(Node *root,int target){
if(root == nullptr){
return;
}
if(root->data == target){
tar = root;
}
if(root->left != nullptr){
par[root->left] =root;
}if(root->right != nullptr){
par[root->right]= root;
}
dfs1(root->left,target);
dfs1(root->right,target);
}
int dfs2(Node* from){
if(from == nullptr){
return 0;
}
int lft = 0, rgt = 0, parent = 0;
vis[from] =true;
if(vis.find(from->left) == vis.end()){
lft = dfs2(from->left);
}
if(vis.find(from->right) == vis.end()){
rgt = dfs2(from->right);
}
if(par.find(from) != par.end() && vis.find(par[from]) == vis.end()){
parent = dfs2(par[from]);
}
return 1 + max(max(lft, rgt), parent);
}
};