Leetcode 270: Closest Binary Search Tree Value

问题描述:
Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

思路:
既然是BST,那么中序遍历可以给我们有序数列。你染可以获得有序数列,我们可以用一次遍历找到最近的那个数

代码如下:

class Solution {
    List<Integer> list=new ArrayList<>();
    public int closestValue(TreeNode root, double target) {
        inOrder(root);
        int i=0;
        while((i<=list.size()-1)&&(target>list.get(i))){
            i++;
        }
        if(i==0)  return list.get(0);
        else if(i==list.size())  return list.get(list.size()-1);
        else return  target<=((double)list.get(i-1)+(double)list.get(i))/2 ? list.get(i-1): list.get(i);
    }
    
    private void inOrder(TreeNode root){
        if(root==null) return;
        inOrder(root.left);
        list.add(root.val);
        inOrder(root.right);
    }
}

时间复杂度:O(n)

二刷:二叉搜索

class Solution {
    public int closestValue(TreeNode root, double target) {
        //最初,closest设为根结点的值
        int closest=root.val;
        //用while循环控制树的遍历:
        while(root!=null){
            //检测之前的closest是否合格
            closest=Math.abs(root.val-target)<Math.abs(closest-target)? root.val: closest;
            //继续寻找,沿着靠近target的方向
            root=target<root.val? root.left:root.right;
        }
        return closest;
    }
}

时间复杂度:O(h), and h is O(logn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值