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.
BST中序遍歷是有序的。求最小值的時候就是看這個節(jié)點和前邊的節(jié)點的值是不是最小值就行了。
代碼如下:

/**
 * 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) {
        finMinValue(root);
        return r;
    }
    //中序遍歷
    void finMinValue(TreeNode* root)
    {
        if(root == NULL)
            return;
        finMinValue(root->left);
        if(pre != -1)
        {
            int v = abs(root->val - pre);
            if(v < r)
                r = v;
        }
        pre = root->val;
        finMinValue(root->right);
    }
private:
    int r = INT_MAX;
    int pre = -1;    
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容