Friday, March 6, 2020

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:

A:


都转成一个数组之后再sort, 然后找

/**
 * 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> V;
        traversal(root, V);
        sort(V.begin(), V.end());
        int res = V[1]-V[0];
        for(int i =1;i<V.size()-1;++i)
            res = min(res, V[i+1]-V[i]);
        return res;
    }
private:
    void traversal(TreeNode* root, vector<int> & V)
    {
        if(not root)
            return;
        V.push_back(root->val);
        traversal(root->left, V);
        traversal(root->right, V);
    }
};




No comments:

Post a Comment