LeetCode-530. Minimum Absolute Difference in BST (Java)

来源:互联网 发布:java递归树形数据结构 编辑:程序博客网 时间:2024/06/02 05:54

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:   1    \     3    /   2Output:1Explanation:The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

----------------------------------------------------------------------------------------------------------------------------------------------------------

这道题是关于二叉搜索树,在解题时,我未注意a binary search tree,虽然测试通过,但耗时过多,在此基础上,求最小值的时候,我每个数与所有的数都做了差,如果注意到二叉搜索树并且了解其性质,则只需要求其相邻的数之差即可。

关于二叉搜索树

若它的左子树不为空,则左子树上所有结点的值均小于等于它的根结点的值;

若它的右子树不为空,则右子树上所有结点的值均大于等于它的根结点的值;

它的左、右子树也分别为二叉查找树。

目的并非为了排序,而是为了提高查找和删除关键字的速度,不管怎么说,在一个有序的数据集上查找,

速度总是要快于无序的数据集。

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

代码如下:

public class Solution {    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(min, root.val - prev);        }        prev = root.val;                getMinimumDifference(root.right);                return min;    }}

二叉搜索树使用中序遍历,得到的结果是已经排序好的,所以只需比较相邻的值即可。

思路如下:求最小差----->对数字进行排序后,相邻做差------->二叉搜索树,中序遍历可得已排序序列。


参考链接:https://discuss.leetcode.com/topic/80823/two-solutions-in-order-traversal-and-a-more-general-way-using-treeset



原创粉丝点击