Maximum Difference Between Node and Ancestor LeetCode solution in C++

1
class Solution {
2
private:
3
int maxDiff;
4
pair<int, int> helper(TreeNode *root) {
5
if (root == NULL) return {INT_MAX, INT_MIN};
6
pair<int, int> L = helper(root->left), R = helper(root->right);
7
pair<int, int> minMax = {min(L.first, R.first), max(L.second, R.second)};
8
if (minMax.first != INT_MAX)
9
maxDiff = max(maxDiff, max(abs(root->val - minMax.first), abs(root->val - minMax.second)));
10
return {min(root->val, minMax.first), max(root->val, minMax.second)};
11
}
12

13
public:
14
int maxAncestorDiff(TreeNode *root) {
15
maxDiff = INT_MIN;
16
helper(root);
17
return maxDiff;
18
}
19
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0