mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
cpp: add “1026. Maximum Difference Between Node and Ancestor”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
5f9d8d328b
commit
744059e7b1
1 changed files with 39 additions and 0 deletions
39
cpp/maximum-difference-between-node-and-ancestor.cpp
Normal file
39
cpp/maximum-difference-between-node-and-ancestor.cpp
Normal 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);
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue