-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1026. Maximum Difference Between Node and Ancestor.cpp
49 lines (42 loc) · 1.34 KB
/
1026. Maximum Difference Between Node and Ancestor.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
// Time complexity - O(N)
// Space complexity- O(height of tree)
typedef pair<int,int> pi;
class Solution {
public:
pi help(TreeNode* root,int& ans)
{
//base case
if(!root)
return {-1,-1};
//recursive calls
//small calculation
auto a=help(root->left,ans);
auto b=help(root->right,ans);
if(a.first!=-1 and b.first!=-1)
{
int maxi=max(a.first,b.first);
int mini=min(a.second,b.second);
ans=max(abs(root->val-maxi),ans);
ans=max(abs(root->val-mini),ans);
return {max(maxi,root->val),min(mini,root->val)};
}
else if(a.first==-1 and b.first!=-1)
{
ans=max(abs(root->val-b.first),ans);
ans=max(abs(root->val-b.second),ans);
return {max(b.first,root->val),min(b.second,root->val)};
}
else if(a.first!=-1 and b.first==-1)
{
ans=max(abs(root->val-a.first),ans);
ans=max(abs(root->val-a.second),ans);
return {max(a.first,root->val),min(a.second,root->val)};
}
return {root->val,root->val};
}
int maxAncestorDiff(TreeNode* root) {
int ans=0;
auto call=help(root,ans);
return ans;
}
};