1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
class Solution { private: void findMaxDiff(TreeNode *root, unordered_map<TreeNode*, int> &minMap, unordered_map<TreeNode*, int> &maxMap, int &maxDiff) { if (!root) return; findMaxDiff(root -> left, minMap, maxMap, maxDiff); findMaxDiff(root -> right, minMap, maxMap, maxDiff); int minVal = root -> val; int maxVal = root -> val; if (root -> left || root -> right) { minVal = INT_MAX; maxVal = INT_MIN; if (root -> left) { minVal = min(minMap[root -> left], minVal); maxVal = max(maxMap[root -> left], maxVal); } if (root -> right) { minVal = min(minMap[root -> right], minVal); maxVal = max(maxMap[root -> right], maxVal); } maxDiff = max({abs(root -> val - minVal), abs(root -> val - maxVal), maxDiff}); minMap[root] = min(minVal, root -> val); maxMap[root] = max(maxVal, root -> val); } else { minMap[root] = minVal; maxMap[root] = maxVal; } } public: int maxAncestorDiff(TreeNode* root) { unordered_map<TreeNode*, int> minMap; unordered_map<TreeNode*, int> maxMap; int maxDiff = 0; findMaxDiff(root, minMap, maxMap, maxDiff); return maxDiff; } };
|