您的位置:首页 > 产品设计 > UI/UE

270. Closest Binary Search Tree Value

2016-03-31 12:35 239 查看
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

Given target value is a floating point.

You are guaranteed to have only one unique value in the BST that is closest to the target.

Solution 1. Iteration
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
double diff = Double.MAX_VALUE;
int val = root.val;

while (root != null) {
if (diff > Math.abs(root.val - target)) {
val = root.val;
diff = Math.abs(root.val - target);
}
if (root.val > target) {
root = root.left;
} else {
root = root.right;
}
}

return val;
}
}

Solution 2. Recursion
public class Solution {
public int closestValue(TreeNode root, double target) {
int a = root.val;
TreeNode kid = target < a ? root.left : root.right;
if (kid == null) return a;
int b = closestValue(kid, target);
return Math.abs(a - target) < Math.abs(b - target) ? a : b;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: