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 is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
求二叉搜索树中任意两个节点差的绝对值最小。
思路:因为二叉搜索树中序遍历是升序的。因此中序遍历的时候就可以检查相邻节点差的绝对值了。
/**
* 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 ans=INT_MAX,before=0;
int flag=1;
int getMinimumDifference(TreeNode* root) {
inorder(root);
return ans;
}
void inorder(TreeNode* root){
if(root){
inorder(root->left);
if(flag==1){
flag=0;
}
else{
ans=min(ans,abs(root->val-before));
}
before=root->val;
inorder(root->right);
}
}
};