LeetCode530. Minimum Absolute Difference in BST

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.

BST 的最小绝对差值。

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.
 public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
 }
 ```

 **方法一:**  
 利用BST的中序遍历是有序的这一性质,一边遍历一边计算差的最小值.
 ```
    int min = Integer.MAX_VALUE;
    Integer prev = null;
    public int getMinimumDifference(TreeNode root) {
        if(root == null) return min;
        getMinimumDifference(root.left);
        if(prev != null){
            min = Math.min(Math.abs(root.val - prev),min);
        }
        prev = root.val;
        getMinimumDifference(root.right);
        return min;    
    }

方法二:
将上面的方法写的更具体,进一步熟悉二叉树的中序遍历的写法.重要,一开始自己不会写。

    public int getMinimumDifference2(TreeNode root){
        List<Integer> list = new ArrayList<>();
        list = select(root);
        int min = Integer.MAX_VALUE;
        for(int i = 1; i < list.size(); i++){
            min = Math.min(Math.abs(list.get(i) - list.get(i-1)), min);
        }
        return min;

    }

    //BST的中序遍历

    public List<Integer> select(TreeNode root){
        List<Integer> list = new ArrayList<>();
        if(root == null) return null;
        inorder(root,list); 
        return list;
    }

    public void inorder(TreeNode root, List<Integer> list){
        if(root.left != null){
            inorder(root.left, list);
        }   
        list.add(root.val);
        if(root.right != null){
            inorder(root.right, list);
        }   
    }

方法三:
思考问题,如果不是BST呢,而是普通的二叉树?
下面的方法是针对普通二叉树的,即使不是BST也适用。

    int min2 = Integer.MAX_VALUE;
    TreeSet<Integer> set = new TreeSet<>();
    public int getMinimumDifference3(TreeNode root){
        if(root == null) return min2;

        if(!set.isEmpty()){
            if(set.floor(root.val) != null){
                min2 = Math.min(min, root.val-set.floor(root.val));
            }
            if(set.ceiling(root.val) != null){
                min2 = Math.min(min, set.ceiling(root.val)-root.val);
            }
        }
        set.add(root.val);
        getMinimumDifference3(root.left);
        getMinimumDifference3(root.right);
        return min2;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值