Minimum Absolute Difference in 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) {
        int last = -1, minimum = INT_MAX;
        if (root == NULL)
            return 0;
        dfs(root, last, minimum);
        return minimum;
    }
    
    void dfs(TreeNode *node, int &last, int &minimum)
    {
        if (node->left)
            dfs(node->left, last, minimum);
        if (last >= 0)
            minimum = min(minimum, abs(node->val-last));
        last = node->val;
        if (node->right)
            dfs(node->right, last, minimum);
    }
};

你可能感兴趣的:(Minimum Absolute Difference in BST)