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
| int maxAncestorDiff(TreeNode* root) { if (root == nullptr) return -1; int minVal, maxVal; return maxAncestorDiff(root, minVal, maxVal); } int maxAncestorDiff1(TreeNode *root, int &minVal, int &maxVal) { if (root == nullptr) return -1; minVal = maxVal = root->val; int d = -1, leftMin, leftMax, rightMin, rightMax; if (root->left) { int r = maxAncestorDiff(root->left, leftMin, leftMax); d = max(r, max(abs(root->val - leftMin), abs(root->val - leftMax))); minVal = min(minVal, leftMin); maxVal = max(maxVal, leftMax); } if (root->right) { int r = maxAncestorDiff(root->right, rightMin, rightMax); d = max(d,max(r, max(abs(root->val - rightMax), abs(root->val - rightMin)))); minVal = min(minVal, rightMin); maxVal = max(maxVal, rightMax); } if (!root->left && !root->right) return -1; return d; }
|