Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is1, which isthe difference between2and1 (orbetween2and3).
Note: There are at least two nodes in this BST.
代码:
struct TreeNode {
intval;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void inorderTraverse(TreeNode* root, int& val, int& min_dif) {
if (root->left != NULL)
inorderTraverse(root->left, val, min_dif);
if (val >= 0)
min_dif = min(min_dif, root->val - val);
val = root->val;
if (root->right != NULL)
inorderTraverse(root->right, val, min_dif);
}
int getMinimumDifference(TreeNode* root) {
auto min_dif = INT_MAX, val = -1;
inorderTraverse(root, val, min_dif);
return min_dif;
}
};