[leetcode]: 530. Minimum Absolute Difference in BST

1.题目描述

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).
给一个二叉搜索树,求两元素的最小绝对差

2.分析

2叉搜索树中序遍历的结果是有序的。
最小绝对差是两个相邻元素之差。因为是非负数,差值最小为0

3.代码

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        int min_d = INT_MAX;
        int preV = -1;
        InOrderTranverse(root, min_d, preV);
        return min_d;
    }
    void InOrderTranverse(TreeNode* root, int& min_d,int& preV) {
        if (root) {
            InOrderTranverse(root->left, min_d, preV);
            if (preV >= 0)
                min_d = min(min_d, root->val - preV);
            preV = root->val;
            InOrderTranverse(root->right, min_d, preV);
        }
    }
};

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