【两次过】Lintcode 1188. BST的最小绝对差

本文探讨了如何在非负值的二叉搜索树中寻找任意两个节点间最小绝对差值的方法。通过中序遍历,利用BST的性质,递归与非递归两种方式实现,最终获取最小绝对差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定具有非负值的二叉搜索树,找到任意两个节点的值之间的最小绝对差值.

样例

输入
   1
    \
     3
    /
   2

输出:
1

说明:
最小绝对差值为1,即2和1(或2和3之间)之差。

注意事项

此BST中至少有两个节点。


解题思路1:

我们知道按中序遍历BST得到的节点值是递增的,题目限定BST中所有节点值非负,因此只需要比较中序遍历时所有相邻节点的绝对差即可得到最小绝对差。这样题目就变成了中序遍历二叉树的问题。

利用二叉搜索树的性质可知,所求值可能出现在以下两处:

  • 根节点左/右子树相邻两个节点之差
  • 根节点左子树最大值和根节点右子树最小值
    那么利用递归,在遍历时记录上一个遍历的节点(pre),然后用当前节点减去pre即可获得相邻节点之差。而且遍历完左子树最后一个节点,进入根节点右子树前,pre刚好为左子树最大值,而此时根节点为右子树最小值,因此可以检测条件2
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    int min = Integer.MAX_VALUE;
    int pre = -1;
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    public int getMinimumDifference(TreeNode root) {
        // Write your code here
        if (root == null)
            return min;
        
        getMinimumDifference(root.left);
        
        if (pre != -1) 
            min = Math.min(min, root.val - pre);
        
        pre = root.val;
        
        getMinimumDifference(root.right);
        
        return min;
    }
    
    

}

解题思路2:

非递归。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    public int getMinimumDifference(TreeNode root) {
        // Write your code here
        Stack<TreeNode> stack = new Stack<>();
        int pre = -1;
        int min = Integer.MAX_VALUE;
        
        while(root!=null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            
            root = stack.pop();
            if(pre != -1)
                min = Math.min(min, root.val - pre);
            
            pre = root.val;
            root = root.right;
        }
        
        return min;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值