力扣-二叉树-530 二叉搜索树的最小绝对差

思路

类似于数组中计算最小绝对差,利用中序遍历是有序的,计算两两元素差

代码

class Solution {
public:
    int minNUM = INT_MAX;
    TreeNode* pre = NULL;
    int getMinimumDifference(TreeNode* root) {
        if(root == nullptr) return minNUM;

        getMinimumDifference(root->left);
        if(pre!=NULL && root->val - pre->val < minNUM){
            minNUM = root->val - pre->val;
        }
        pre = root;
        getMinimumDifference(root->right);

        return minNUM;
    }
};

你可能感兴趣的:(力扣,#,二叉树,leetcode,算法,数据结构)