美文网首页
530. Minimum Absolute Difference

530. Minimum Absolute Difference

作者: 刘小小gogo | 来源:发表于2018-08-19 17:23 被阅读0次
image.png

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 getMinimumDifference(TreeNode* root) {
        vector<int>ans;
        inorder(root, ans);
        int mindif = INT_MAX;
        for(int i = 1; i < ans.size(); i++){
            if(abs(ans[i] - ans[i-1]) < mindif){
                mindif = abs(ans[i] - ans[i-1] );
            }
        }
        return mindif;
    }
private:
    void inorder(TreeNode* root, vector<int>& num){
        if(root == NULL){
            return;
        }
        inorder(root->left, num);
        num.push_back(root->val);
        inorder(root->right,num);
    }
};

相关文章

网友评论

      本文标题:530. Minimum Absolute Difference

      本文链接:https://www.haomeiwen.com/subject/tgnciftx.html