LeetCode 270. Closest Binary Search Tree Value

我们可以利用二分搜索树的特点 (左<根<右) 来快速定位,由于根节点是中间值,在往下遍历时,根据目标值和根节点的值大小关系来比较。如果节点值大于目标值,则应该找更小的值,于是到左子树去找,反之去右子树找。代码如下:

Solution 1 (Recursive)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int res = root.val;
        return inOrder(root, target, res);
    }
    
    private int inOrder(TreeNode root, double target, int res){
        // base case
        if(root == null){
            return res;
        }else if(root.val == target){
            return root.val;
        }
        // recursive rule
        if(Math.abs(root.val - target) < Math.abs(res - target)){
            res = root.val;
        }
        if(root.val > target){
            res = inOrder(root.left, target, res);
        }else{
            res = inOrder(root.right, target, res);
        }
        return res;
    }
}

Solution 2 (Iterative)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int res = root.val;
        TreeNode curr = root;
        while(curr != null){
            if(Math.abs(curr.val - target) < Math.abs(res - target)){
                res = curr.val;
            }
            curr = curr.val > target ? curr.left : curr.right;
        }
        return res;
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值