【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
题目地址:http://leetcode.com/problems/closest-binary-search-tree-value/
题目描述:
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
1. Given target value is a floating point.
2. You are guaranteed to have only one unique value in the BST that is closest to the target.
Solution1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
* time : O(logn)
* space : O(1)
* 用两种方法,迭代和递归
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
int res = root.val;
while(root != null) {
if(Math.abs(target - root.val) >Math.abs(target - res){
res = root.val;
}
root = root.val > target ? rot.left : root.right;
return res;
}
}
Solution2:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
* time : O(logn)
* space : O(1)
* 用两种方法,迭代和递归
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
return helper(root,target,root.val);
}
public int helper(TreNode root,double target,int val){
if(root == null) return val;
if(Math.abs(root.val == target) < Math.abs(val - target)){
val = root.val;
}
if(root.val < target){
val = helper(root.right , target , val);
}else if(root.val > target){
val = helper(root.left,target,val);
}
return val;
}
}
Date:2018年4月3日