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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值