530. Minimum Absolute Difference in BST

Posted phdeblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

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.

解题:求二叉排序树上任意两个结点之间的最小差值。BST,又称二叉排序树,满足“左结点的值永远小于根结点的值,右结点的值永远大于根结点的值”这个条件。中序遍历所得到的序列顺序,便是将结点的值从小到大排列所得到顺序。那么,这个题目就迎刃而解了,要想val值相差最小,那么必定是中序遍历时相邻的两个结点。所以在中序遍历的过程中,保存父节点的值,计算父节点与当前结点的差值,再与min值相比较,如果比min小,则更新min,反之继续遍历。代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     private int min = Integer.MAX_VALUE;
12     private int pre = -1;//保存父节点的值
13     
14     public int getMinimumDifference(TreeNode root) {
15         if(root == null)
16             return min;
17         getMinimumDifference(root.left);
18         if(pre != -1)
19             min = Math.min(min, Math.abs(root.val - pre));
20         pre = root.val;
21         getMinimumDifference(root.right);
22         return min;
23     }
24 }

也有其他的方法,比如通过java中的排序树来做,代码如下:

public class Solution {
    TreeSet<Integer> set = new TreeSet<>();
    int min = Integer.MAX_VALUE;
    
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return min;
        
        if (!set.isEmpty()) {
            if (set.floor(root.val) != null) {
                min = Math.min(min, root.val - set.floor(root.val));
            }
            if (set.ceiling(root.val) != null) {
                min = Math.min(min, set.ceiling(root.val) - root.val);
            }
        }
        
        set.add(root.val);
        
        getMinimumDifference(root.left);
        getMinimumDifference(root.right);
        
        return min;
    }
}

TreeSet中的  floor( )  函数能返回小于等于给定元素的最大值, ceiling() 函数能返回大于等于给定元素的最小值,其时间开销为对数级,还是挺快的。

参考博客:https://www.cnblogs.com/zyoung/p/6701364.html

 

以上是关于530. Minimum Absolute Difference in BST的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-530-Minimum Absolute Difference in BST]

Leetcode 530. Minimum Absolute Difference in BST

530. Minimum Absolute Difference in BST(LeetCode)

530. Minimum Absolute Difference in BST

[LeetCode] 530. Minimum Absolute Difference in BST Java

easy530. Minimum Absolute Difference in BST