1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

cpp: add “1026. Maximum Difference Between Node and Ancestor”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-11 15:19:44 +01:00
parent 5f9d8d328b
commit 744059e7b1
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,39 @@
#include <limits>
/**
* 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 {
int maxAncestorDiff(TreeNode *node, int lower, int upper) const {
if (node == nullptr) {
return 0;
}
auto diff =
std::max(std::abs(node->val - lower), std::abs(node->val - upper));
auto [next_lower, next_upper] = std::make_tuple(
std::min(lower, node->val), std::max(upper, node->val));
diff =
std::max(diff, maxAncestorDiff(node->left, next_lower, next_upper));
diff = std::max(diff,
maxAncestorDiff(node->right, next_lower, next_upper));
return diff;
}
public:
int maxAncestorDiff(TreeNode *root) {
auto default_bound = root != nullptr ? root->val : 0;
return maxAncestorDiff(root, default_bound, default_bound);
}
};