270. 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: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.
乍一看, 感觉好复杂, 觉得最接近的值或者左子树最大值或者右子树最小值, 如果你也这么想就错了, 因为此时最接近的值应该为root, 啊哈哈~~~w(゚Д゚)w

递归, 但同样是递归, Stefan 大神的就漂亮好多, 膜拜!!!

public int closestValue(TreeNode root, double target) {
       TreeNode child =  target > root.val ? root.right : root.left;
       if(child == null){
              return root.val;
       }
       int val = closestValue(child, target);
       return Math.abs(val - target) < Math.abs(root.val - target) ? val : root.val;
}

public int closestValue(TreeNode root, double target) {
         if(root == null){
                  return target < 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
         }
         if(target > root.val){
                int val = closestValue(root.right, target);
                return (Math.abs(val - target) - Math.abs(root.val - target))
                            < 0 ? val: root.val;
         }else if(target < root.val){
                 int val = closestValue(root.left, target);
                 return Math.abs(val - target) - Math.abs(root.val - target)
                            < 0 ? val : root.val;
         }else{
                 return root.val;
         }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容