From 744059e7b1e963753f636e78f6bfb1cd29a110ba Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 11 Jan 2024 15:19:44 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=E2=80=9C1026.=20Maximum=20Differe?= =?UTF-8?q?nce=20Between=20Node=20and=20Ancestor=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...m-difference-between-node-and-ancestor.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 cpp/maximum-difference-between-node-and-ancestor.cpp diff --git a/cpp/maximum-difference-between-node-and-ancestor.cpp b/cpp/maximum-difference-between-node-and-ancestor.cpp new file mode 100644 index 0000000..6c12812 --- /dev/null +++ b/cpp/maximum-difference-between-node-and-ancestor.cpp @@ -0,0 +1,39 @@ +#include + +/** + * 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); + } +};