530. 二叉搜索树的最小绝对差

给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。

示例 :

输入:

   1
    \
     3
    /
   2

输出:
1

解释:
最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
注意: 树中至少有2个节点。
class Solution {
    int min = Integer.MAX_VALUE;
    TreeNode pre = null;
    public void dfs(TreeNode root){
        if(root != null){
            dfs(root.left);
            if(pre != null)
                min = Math.min(min,Math.abs(root.val - pre.val));
            pre = root;
            dfs(root.right);
        }

    }
    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return min;
    }
}
class Solution {
    List<Integer> list = new ArrayList();
    public void dfs(TreeNode root){
        if(root != null){
            dfs(root.left);
            list.add(root.val);
            dfs(root.right);
        }

    }
    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        int min = Math.abs(list.get(1) - list.get(0));
        for(int i=0;i<list.size()-1;i++){
            int value = Math.abs(list.get(i+1) - list.get(i));
            if(min > value)
                min = value;
        }
        return min;
    }
}

注意:min的初值不能设为0!求最小值,应该把它设置为一个足够大的值,或者是初值。

猜你喜欢

转载自blog.csdn.net/xuchonghao/article/details/80773532
今日推荐