1. 程式人生 > >530. Minimum Absolute Difference in BST

530. Minimum Absolute Difference in BST

http floor != quest inpu min 差值 question 題目

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