forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1026.cpp
More file actions
54 lines (47 loc) · 1.56 KB
/
1026.cpp
File metadata and controls
54 lines (47 loc) · 1.56 KB
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
/**
* 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:
unordered_map<TreeNode*, pair<int,int>>m;
void dfs(TreeNode* root){
if(!root)
return;
else if(!root->left && !root->right){
m[root] = {root->val, root->val};
}
else if(root->left && !root->right){
dfs(root->left);
m[root] = {min(root->val, m[root->left].first), max(root->val, m[root->left].second)};
}
else if(!root->left && root->right){
dfs(root->right);
m[root] = {min(root->val, m[root->right].first), max(root->val, m[root->right].second)};
}
else{
dfs(root->left);
dfs(root->right);
auto it = m[root->left];
auto it2 = m[root->right];
int mi = min(root->val, min(it.first, it2.first));
int n = max(root->val, max(it.second, it2.second));
m[root] = {mi,n};
}
}
int maxAncestorDiff(TreeNode* root) {
dfs(root);
int maxi = INT_MIN;
for(auto it = m.begin(); it != m.end(); it++){
maxi = max(maxi, max(abs(it->first->val- it->second.first), abs(it->first->val- it->second.second)));
}
return maxi;
}
};