LeetCode 530. Minimum Absolute Difference in BST
28 Jul 2018Description:
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Note:
- There are at least two nodes in this BST.
Example:
input:
1 \ 3 / 2
output:
output:
1
explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
if (root == NULL) {
return -1;
}
int minDiff = numeric_limits<int>::max();
findMinDiff(root, minDiff);
return minDiff;
}
void findMinDiff(TreeNode *root, int &minDiff) {
if(root->left != NULL){
recursiveFindDiff(root->left, root->val, minDiff);
findMinDiff(root->left, minDiff);
}
if (root->right != NULL) {
recursiveFindDiff(root->right, root->val, minDiff);
findMinDiff(root->right, minDiff);
}
}
void recursiveFindDiff(TreeNode *node, int comVal, int &minDiff) {
minDiff = min(minDiff, abs(node->val - comVal));
if (node->left != NULL) {
recursiveFindDiff(node->left, comVal, minDiff);
}
if (node->right != NULL) {
recursiveFindDiff(node->right, comVal, minDiff);
}
}
};
There are two layer of recursive passes in the algorithm. The first layer iterates through the entire binary tree; the second layer compute the minimum difference between the current node and the rest of the binary tree. The final result would be the minima of all differences.