问题描述:
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)