530. 二叉搜索树的最小绝对差

530. 二叉搜索树的最小绝对差


题目链接:530. 二叉搜索树的最小绝对差

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        vector<int> res;
        inOrder(root,res);
        int dif=INT_MAX;

        //res已经有序,挨个相减直接找就行
        for(int i=1;i<res.size();i++)
        {
            int tempDif=res[i]-res[i-1];
            if(tempDif<dif)
                dif=tempDif;
        }

        return dif;
    }

    //中序遍历
    void inOrder(TreeNode* root,vector<int>& res)
    {
        if(root==nullptr)   
            return;
        
        inOrder(root->left,res);
        res.push_back(root->val);
        inOrder(root->right,res);
    }
};

你可能感兴趣的:(leetcode,c++)