文章目录
1、题目描述2、解题思路3、解题代码
1、题目描述
2、解题思路
算法有三个数字:当前结点的值 val、目标值 target、最接近目标值的数 closest。
初始时,val == closest == root.val;
1、更新 val == root.val,比较 (val - targrt) 和 (closest - target) 的大小,更新 closest 为小的那个;
2、往 root 的一个子树方向走,target 如果小于 root.val,更新 root = root.left;反之更新 root = root.right。
当 root == null 时,比较完毕,返回 closest。
3、解题代码
class Solution {
public int closestValue(TreeNode root
, double target
) {
int val
= root
.val
;
int closest
= root
.val
;
while (root
!= null
) {
val
= root
.val
;
closest
= Math
.abs(val
- target
) < Math
.abs(closest
- target
) ? val
: closest
;
root
= target
< root
.val
? root
.left
: root
.right
;
}
return closest
;
}
}