-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC-1026. Maximum Difference Between Node and Ancestor
45 lines (40 loc) · 1.34 KB
/
LC-1026. Maximum Difference Between Node and Ancestor
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
/**
* 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:
int result = INT_MIN;
pair<int,int> solve(TreeNode* root) // postorder traversal
{
if(!root) return {INT_MIN,INT_MAX};
if(root->left == NULL && root->right == NULL)
{
//cout << root->val << " ";
return {root->val,root->val};
}
pair<int,int> l(INT_MIN,INT_MAX);
pair<int,int> r(INT_MIN,INT_MAX);
l = solve(root->left); // left call
r = solve(root->right); // right call
pair<int,int> s(INT_MIN,INT_MAX); // my root work
s.first = max(l.first,r.first);
s.second = min(l.second,r.second);
result = max(result,max(abs(root->val-s.first),abs(root->val-s.second)));
s.first = max(root->val,s.first);
s.second = min(root->val,s.second);
return s;
}
int maxAncestorDiff(TreeNode* root)
{
solve(root);
return result;
}
};