LeetCode530. Minimum Absolute Difference in BST

来源:互联网 发布:网页视频剪辑软件 编辑:程序博客网 时间:2024/06/05 02:21

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;    }
原创粉丝点击