add: 230418-CN

This commit is contained in:
Eatswap 2023-04-19 01:25:52 +08:00
parent 6b5ae005d9
commit 0ba5fb7cb8
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 40 additions and 1 deletions

39
cpp/2304/230418-CN.cpp Normal file
View File

@ -0,0 +1,39 @@
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {}
};
/**
* 1026. Maximum Difference Between Node and Ancestor
*
* Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
* A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
*/
class Solution {
private:
static inline constexpr int MAX(int x, int y) { return x > y ? x : y; }
static inline constexpr int MIN(int x, int y) { return x < y ? x : y; }
static inline constexpr int ABS(int x) { return x < 0 ? -x : x; }
static int dfs(TreeNode*, int, int);
public:
static int maxAncestorDiff(TreeNode*);
};
int Solution::maxAncestorDiff(TreeNode* r) {
return r ? dfs(r, r->val, r->val) : 0;
}
int Solution::dfs(TreeNode* n, int min, int max) {
int ret = MAX(ABS(n->val - min), ABS(n->val - max));
const int min_ = MIN(min, n->val), max_ = MAX(max, n->val);
if (n->left)
ret = MAX(ret, dfs(n->left, min_, max_));
if (n->right)
ret = MAX(ret, dfs(n->right, min_, max_));
return ret;
}

View File

@ -4,4 +4,4 @@ PROJECT(2304)
SET(CMAKE_CXX_STANDARD 23)
SET(CMAKE_EXPORT_COMPILE_COMMANDS true)
ADD_EXECUTABLE(2304 230418.cpp)
ADD_EXECUTABLE(2304 230418-CN.cpp)