Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
public class Solution {
public int closestValue(TreeNode root,
double target)
{
int closestVal =
root.val;
while(root!=
null)
{
closestVal = (Math.abs(target-root.val) < Math.abs(target-closestVal))?
root.val:closestVal;
if(closestVal == target)
return root.val;
root = (root.val > target)?
root.left:root.right;
}
return closestVal;
}
}
转载于:https://www.cnblogs.com/hygeia/p/5104289.html
相关资源:JAVA上百实例源码以及开源项目