LeetCode 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.

/**
 * 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:
    void inorder(TreeNode* root){//利用BST中序遍历的性质
        if(root==NULL)
            return;
        inorder(root->left);
        minval=min(minval,root->val-temp);
        temp=root->val;
        inorder(root->right);
    }
    int getMinimumDifference(TreeNode* root) {
        inorder(root);
        return minval;
    }
private:
    int minval=999999;
    int temp=-999999;
};
posted @ 2018-12-05 22:30  A-Little-Nut  阅读(105)  评论(0编辑  收藏  举报