啊 最直观的应该是iterative的 每次向下一层 都尝试更新min dist就好 不会因为选择了某一边而错过min dist的!因为假如root 比target大 那root右边那些更大的不可能比root更近!
public class Solution {
public int closestValue(TreeNode root, double target) {
int close = root.val;
while ( root != null ){
if ( Math.abs ( close - target ) > Math.abs ( root.val - target ) )
close = root.val;
root = root.val > target ? root.left : root.right;
}
return close;
}
}
recursive
public class Solution {
public int closestValue(TreeNode root, double target) {
int rootval = root.val;
TreeNode c = rootval > target ? root.left : root.right;
if ( c == null )
return rootval;
int close = closestValue ( c, target );
return Math.abs ( close - target ) > Math.abs ( rootval - target ) ? rootval : close;
}
}