530. 二叉搜索树的最小绝对差

530. 二叉搜索树的最小绝对差

class Solution {
    
    public int getMinimumDifference(TreeNode root) {
        int leftMin = Integer.MAX_VALUE;
        int rightMin = Integer.MAX_VALUE;
        int minl = Integer.MAX_VALUE;
        int minr = Integer.MAX_VALUE;
        if(root.left != null){
            TreeNode left = root.left;
            while(left.right != null){
                left = left.right;
            }
            minl = Math.abs(root.val - left.val);
            leftMin = getMinimumDifference(root.left);
        }
        if(root.right != null){
            TreeNode right = root.right;
            while(right.left != null){
                right = right.left;
            }
            minr = Math.abs(root.val - right.val);
            rightMin = getMinimumDifference(root.right);
        }
        return Math.min(Math.min(minl,minr),Math.min(leftMin,rightMin));
    }
}

思路:

当前节点记录4个最小值:

1.节点值与左子树中的最大值的差

2.节点值与右子树中的最小值的差

3.左子树中的最小差值

4.右子树中的最小差值

取这4个值的最小差值return

因为是二叉搜索树,中序遍历是升序数组,只要记录前后节点的差值,取最小就好

DFS版本

class Solution {
    TreeNode pre;
    int result = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return result;
    }
    public void dfs(TreeNode node){
        if(node == null) return;
        dfs(node.left);
        if(pre != null){
            result = Math.min(result,Math.abs(node.val - pre.val));
        }
        pre = node;
        dfs(node.right);
    }
}

 迭代法

class Solution {
    
    
    public int getMinimumDifference(TreeNode root) {
        Deque<TreeNode> st = new LinkedList<>();
        TreeNode pre = new TreeNode(-1);
        TreeNode cur = root;
        int result = Integer.MAX_VALUE;
        
        while(!st.isEmpty() || cur != null){
            if(cur != null){                                    //左
                st.addLast(cur);
                cur = cur.left;
            }else{                                              //中
                cur = st.pollLast();
                if(pre.val != -1) result = Math.min(result,cur.val - pre.val);
                pre = cur;
                cur = cur.right;                                //右
            }
        }
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值