-
Notifications
You must be signed in to change notification settings - Fork 0
/
Burning Tree.cpp
72 lines (64 loc) · 1.56 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
// Time complexity - O(N)
// Space complexity- O(H*3)
class Sagar{
public:
bool isFound=0;
int height=0;
int ans=0;
Sagar(){
isFound=0;
height=0;
ans=0;
}
};
class Solution {
public:
Sagar help(Node* root,int& target)
{
// base case
if(!root)
{
Sagar temp;
return temp;
}
// recursive calls
// and small calculation
Sagar left=help(root->left,target);
Sagar right=help(root->right,target);
// if current node is our target node
if(root->data==target)
{
Sagar temp;
temp.height=1;
temp.ans=max(left.height,right.height);
temp.isFound=1;
return temp;
}
// if current node is not targeted node
if(left.isFound)
{
Sagar temp;
temp.height=left.height+1;
temp.isFound=1;
temp.ans=max({left.ans,right.ans,left.height+right.height});
return temp;
}
if(right.isFound)
{
Sagar temp;
temp.height=right.height+1;
temp.isFound=1;
temp.ans=max({left.ans,right.ans,left.height+right.height});
return temp;
}
Sagar temp;
temp.isFound=0;
temp.height=max(left.height,right.height)+1;
return temp;
}
int minTime(Node* root, int target)
{
Sagar ans=help(root,target);
return ans.ans;
}
};