-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-1026.cpp
More file actions
32 lines (27 loc) · 858 Bytes
/
Problem-1026.cpp
File metadata and controls
32 lines (27 loc) · 858 Bytes
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
// Problem - 1026
// https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/
// O(n) time complexity and O(n) space complexity solution using bottom up dfs
class Solution {
public:
int ans = 0;
pair <int, int> maxDiff(TreeNode* root) {
if(!root) {
return {-1, 1e5+1};
}
if(!root->left && !root->right){
return {root->val, root->val};
}
auto lv = maxDiff(root->left);
auto rv = maxDiff(root->right);
int mn = min(lv.second, rv.second);
int mx = max(lv.first, rv.first);
ans = max({ans, abs(mn - root->val), abs(mx - root->val)});
mx = max(root->val, mx);
mn = min(root->val, mn);
return {mx, mn};
}
int maxAncestorDiff(TreeNode* root) {
maxDiff(root);
return ans;
}
};