Maximum Difference Between Node and Ancestor LeetCode solution in C++
1class Solution {2private:3int maxDiff;4pair<int, int> helper(TreeNode *root) {5if (root == NULL) return {INT_MAX, INT_MIN};6pair<int, int> L = helper(root->left), R = helper(root->right);7pair<int, int> minMax = {min(L.first, R.first), max(L.second, R.second)};8if (minMax.first != INT_MAX)9maxDiff = max(maxDiff, max(abs(root->val - minMax.first), abs(root->val - minMax.second)));10return {min(root->val, minMax.first), max(root->val, minMax.second)};11}1213public:14int maxAncestorDiff(TreeNode *root) {15maxDiff = INT_MIN;16helper(root);17return maxDiff;18}19};