啊 最直观的应该是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;
}
}

本文探讨了在树形结构中查找与目标值最接近的元素的高效算法,通过迭代和递归两种方法实现了优化过程。
331

被折叠的 条评论
为什么被折叠?



