530. Minimum Absolute Difference in BST

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 prev = -1;
    int min = INT_MAX;
    void GetMinDeff(TreeNode *root){
        if(root == NULL)    return;
        
        GetMinDeff(root->left);
        int diff;
        if(prev == -1)
            prev = root->val;
        else{
            diff = fabs(root->val - prev);
            if(min > diff)
                min = diff;
            prev = root->val;
        }
        GetMinDeff(root->right);
    }
    int getMinimumDifference(TreeNode* root) {
        GetMinDeff(root);
        return min;
        
    }
};

 

最小值

posted @ 2017-03-10 14:02  Hutonm  阅读(269)  评论(0编辑  收藏  举报