java - 在 BST 中查找最接近值的问题
问题描述
我正在尝试编写一个函数,该函数接受 BST 和目标整数值,并返回与 BST 中包含的目标值最接近的值。
但是,我的代码是 0 而不是 10,这是这种情况的答案
谁能解释我的错误的基本概念?
public static int findClosestValueInBst(BST tree, int target) {
int globalDiff = Integer.MAX_VALUE;
int answer = 0;
subFunction(tree, target, globalDiff, answer);
return answer;
}
private static void subFunction (BST tree, int target, int globalDiff, int answer) {
if (tree == null) {
return;
}
int localDiff = Math.abs(target - tree.value);
if (localDiff < globalDiff) {
globalDiff = localDiff;
answer = tree.value;
}
subFunction(tree.left, target, globalDiff, answer);
subFunction(tree.right, target, globalDiff, answer);
return;
}
public static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
public static void main (String[] args) {
BST first = new BST(1);
BST second = new BST(2);
BST third = new BST(10);
BST fourth = new BST(5);
BST fifth = new BST(4);
first.left = second;
first.right = third;
second.left = fourth;
second.right = fifth;
System.out.println(findClosestValueInBst(first, 11));
}
解决方案
推荐阅读
- c++ - 使用 Qt 将应用程序的功能拆分为插件
- java - Java BigDecimal.ROUND_HALF 偶数,带 3 位小数(奇数和偶数)
- react-native-android - 谷歌像素2 XL中的本机应用程序显示透明的底部按钮栏
- android - Android 与 NGDC 磁偏角 API 差异
- amazon-s3 - hive - 使用外部或本地 s3 而不是 aws s3
- javascript - 无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个无操作,但它表明您的应用程序中存在内存泄漏
- product - 两种产品,不同的到货时间,Anylogic
- asp.net-mvc - 在.NET MVC 中使用@Ajax.BeginForm 上传图片?
- swift - 让 Sprite 慢慢向触摸方向移动
- python-3.x - Create a line graph per bin in Python 3