Skip to content

Commit

Permalink
Day 18: q1: Maximum Difference Between Node and Ancestor #396 cpp cod…
Browse files Browse the repository at this point in the history
…e done
  • Loading branch information
Akansha77 committed Jan 26, 2024
1 parent 58e95e1 commit 4660a83
Showing 1 changed file with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* 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 {
public:
int maxAncestorDiff(TreeNode* root) {
int m = 0;
dfs(root, m);
return m;
}

private:
std::pair<int, int> dfs(TreeNode* root, int& m) {
if (root == nullptr) {
return {INT_MAX, INT_MIN};
}

auto left = dfs(root->left, m);
auto right = dfs(root->right, m);

int minVal = std::min(root->val, std::min(left.first, right.first));
int maxVal = std::max(root->val, std::max(left.second, right.second));

m = std::max({m, std::abs(minVal - root->val), std::abs(maxVal - root->val)});

return {minVal, maxVal};
}
};

0 comments on commit 4660a83

Please sign in to comment.