码迷,mamicode.com
首页 > 其他好文 > 详细

530. Minimum Absolute Difference in BST

时间:2018-06-07 14:13:24      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:root   二叉排序树   大于   ref   参考   amp   过程   ret   最小值   

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

标签:root   二叉排序树   大于   ref   参考   amp   过程   ret   最小值   

原文地址:https://www.cnblogs.com/phdeblog/p/9149547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!