530 Minimum Absolute Difference in BST
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).Last updated
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).Last updated
int getMinimumDifference(TreeNode* root) {
int prev = INT_MAX, my_min = INT_MAX;
getMinimumDifferenceRec(root, prev, my_min);
return my_min;
}
void getMinimumDifferenceRec(TreeNode* root, int &prev, int &my_min) {
if (root) {
getMinimumDifferenceRec(root->left, prev, my_min);
my_min = min(my_min, abs(root->val - prev));
prev = root->val;
getMinimumDifferenceRec(root->right, prev, my_min);
}
}