530. 二叉搜索樹的最小絕對差(樹)(BST)

在這裏插入圖片描述
方法一:(中序遍歷+額外o(n)的存儲空間)
中序遍歷BST ,得到的序列有序,所有相鄰結點差的絕對值的最小值就是要找的結果

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int getMinimumDifference(TreeNode root) {
        ArrayList<Integer> array = new ArrayList<>();
        inOrder(root,array);
        int res = Integer.MAX_VALUE;
        if(array.size()<2) return -1;
        for(int i = 1;i<array.size();i++){
            if(array.get(i)-array.get(i-1)<res) res = array.get(i)-array.get(i-1);
        }
        return res;
    }

    public void inOrder(TreeNode root, ArrayList array){
        if(root == null) return;
        inOrder(root.left,array);
        array.add(root.val);
        inOrder(root.right,array);
    }
}

方法二:中序遍歷+只是用常數量輔助空間

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private int res = Integer.MAX_VALUE;
    private TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {
        inOrder(root);
        return res;
    }

    public void inOrder(TreeNode root){
        if(root == null) return;
        inOrder(root.left);
        
        if(pre!=null) res = Math.min(res,root.val-pre.val);
        pre = root;

        inOrder(root.right);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章