-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1026.cpp
29 lines (29 loc) · 913 Bytes
/
1026.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
// Runtime: 8 ms, faster than 92.53% of C++ online submissions for Maximum
// Difference Between Node and Ancestor.
public:
int maxAncestorDiff(TreeNode *root) {
int ret = 0;
function<void(TreeNode *, int, int)> recursion =
[&ret, &recursion](auto root, auto maxVal, auto minVal) {
ret = max({abs(maxVal - root->val), abs(minVal - root->val), ret});
maxVal = max(root->val, maxVal);
minVal = min(root->val, minVal);
if (root->left)
recursion(root->left, maxVal, minVal);
if (root->right)
recursion(root->right, maxVal, minVal);
};
recursion(root, root->val, root->val);
return ret;
}
};