forked from Nandinig24/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1026
70 lines (58 loc) · 1.46 KB
/
1026
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root,vector<int>&v){
if(root==NULL)
return ;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
void subgraph(TreeNode* root,vector<pair<int,vector<int>>>&mp){
// vector<int>v;
if(root==NULL)
return ;
subgraph(root->left,mp);
vector<int>v;
inorder(root,v);
if(v.size()>0)
mp.push_back({root->val,v});
subgraph(root->right,mp);
}
int maxAncestorDiff(TreeNode* root) {
// map<int,vector<int>>∓
vector<pair<int,vector<int>>>mp;
vector<int>ans;
subgraph(root,mp);
// for(auto i:mp){
// int a=i.first;
// cout<<"a is"<<a<<endl;
// vector<int>v=i.second;
// for(auto j:v)
// cout<<j<<" ";
// cout<<endl;
// }
for(auto i:mp){
int a=i.first;
vector<int>v=i.second;
if(v.size()>1){
sort(v.begin(),v.end());
int a1=abs(a-v[v.size()-1]);
int b1=abs(a-v[0]);
int mx=max({a1,b1});
ans.push_back(mx);
}
}
return *max_element(ans.begin(),ans.end());
}
};