这道题让自己有种开发智力的赶脚,请再好好看看,尤其是第一种递归解法。
有两种解法。
/**
* 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) {
TreeNode kid = null;
if (root.val > target) {
kid = root.left;
} else {
kid = root.right;
}
if (kid == null) {
return root.val;
}
int closest = closestValue(kid, target);
return Math.abs(root.val - target) < Math.abs(closest - target) ? root.val : closest;
}
// public int closestValue(TreeNode root, double target) {
// //int closest = 0;
// int closest = root.val;
// while (root != null) {
// closest = Math.abs(root.val - target) < Math.abs(closest - target) ? root.val : closest;
// root = root.val > target ? root.left : root.right;
// }
// return closest;
// }
}