【一次过】Lintcode 900. 二叉搜索树中最接近的值

给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值

样例

样例1

输入: root = {5,4,9,2,#,8,10} and target = 6.124780
输出: 5

样例2

输入: root = {3,2,4,1} and target = 4.142857
输出: 4

注意事项

  • 给出的目标值为浮点数
  • 我们可以保证只有唯一一个最接近给定值的节点

解题思路1:

非递归,使用cnt变量存储当前最小差值,res为最接近的值。然后依照BST性质遍历。

/**
 * 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 given BST
     * @param target: the given target
     * @return: the value in the BST that is closest to the target
     */
    public int closestValue(TreeNode root, double target) {
        // write your code here
        double cnt = Double.MAX_VALUE;  //记录最小差值
        int res = 0;
        
        while(root != null){
            if(Math.abs(target - root.val) < cnt){
                cnt = Math.abs(target - root.val);
                res = root.val;
            }
            
            if(target > root.val)
                root = root.right;
            else
                root = root.left;
        }
        
        return res;
    }
}

解题思路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 given BST
     * @param target: the given target
     * @return: the value in the BST that is closest to the target
     */
    public int closestValue(TreeNode root, double target) {
        // write your code here
        res = root.val;
        
        helper(root, target);
        
        return res;
    }
    
    private int res;
    
    private void helper(TreeNode root, double target){
        if(root == null)
            return;
            
        if(Math.abs(target - root.val) < Math.abs(target - res))
            res = root.val;
            
        if(target > root.val)
            helper(root.right, target);
        else
            helper(root.left, target);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值