generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
39 lines (32 loc) · 1.04 KB
/
solution.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
30
31
32
33
34
35
36
37
38
39
#include <set>
class Solution {
public:
int maxAncestorDiff(TreeNode* root) {
std::multiset<int> ancestors{root->val};
return maxDifferences(ancestors, root);
}
int maxDifferences(std::multiset<int>& ancestors, TreeNode* node) {
int differences = std::max(
std::abs(*ancestors.begin() - node->val),
std::abs(*ancestors.rbegin() - node->val));
if (node->left == nullptr && node->right == nullptr) {
return differences;
}
ancestors.insert(node->val);
if (node->left != nullptr) {
if (node->right != nullptr) {
differences = std::max(
differences,
std::max(
maxDifferences(ancestors, node->left),
maxDifferences(ancestors, node->right)));
} else {
differences = std::max(differences, maxDifferences(ancestors, node->left));
}
} else if (node->right != nullptr) {
differences = std::max(differences, maxDifferences(ancestors, node->right));
}
ancestors.erase(node->val);
return differences;
}
};