java - 方法进入第二次返回,导致错误输出
问题描述
我正在尝试使用 Java 在二叉树中查找特定节点。我查找节点的方法返回包含所搜索数据的节点。
我的代码如下所示:
public BinNode find(Comparable item) throws NullPointerException {
if (item == null) {
throw new NullPointerException("item is NULL");
} else if (root == null) {
throw new NullPointerException("tree is empty");
}
return find(root, item);
}
public static boolean found = false;
public BinNode find(BinNode k, Comparable item) throws NullPointerException {
if (k.getData().equals(item)) {
found = true;
return k;
}
if (!found && k.getChildLeft() != null) {
find(k.getChildLeft(), item);
}
if (!found && k.getChildRight() != null) {
find(k.getChildRight(), item);
}
return k;
}
运行调试器我可以看到,当我搜索树中存在的项目时,它将找到正确的节点并在“found”设置为 true 后转到第一个返回语句。但是,编译器不会将该节点返回给方法调用,而是继续执行第二个返回语句,返回根。所以无论 Node 位于何处,该方法将始终返回根。
我究竟做错了什么?
解决方案
您的方法永远不会返回“未找到”,这从根本上是错误的,因为大多数时候项目不在数据中。这是你的主要问题。您需要在底部语句中返回null
/ 一个空。然后你需要在向下遍历树时正确处理“未找到”的返回值,即在你调用左右孩子的地方。Optional
return
find
您的逻辑必须始终是:
- 使当前节点具有正确的值
- 如果是,则返回当前节点
- 左节点是否包含值
- 如果是,则从左侧返回相应的节点
- 右节点是否包含值
- 如果是,则从右侧返回相应的节点
- 返回“未找到”(因为当前节点不正确,左右都不包含值)
您当前跳过/尚未实现两个嵌套的“如果是,则从左/右返回相应的节点”代码路径。
(当然删除found
评论中提到的变量)
public BinNode find(BinNode k, Comparable item) throws NullPointerException {
if (k.getData().equals(item)) {
return k;
}
if (k.getChildLeft() != null) {
BinNode node = find(k.getChildLeft(), item);
if (node != null) return node;
}
if (k.getChildRight() != null) {
BinNode node = find(k.getChildRight(), item);
if (node != null) return node;
}
return null;
}
推荐阅读
- linux - Linux Shell“粘贴”命令 - 保证基于行的交错?
- javascript - 在选择选项中更改图像
- git - 错误 /opt/stack/devstack/functions-common:629 git 调用失败:git clone https://opendev.org/openstack/requirements.git
- hl7-fhir - Asymmetrik FHIR mongo:部分患者已存储
- reactjs - React Native:“渲染的钩子比预期的要少。” 不知道这意味着什么,应用程序崩溃?
- xamarin.forms - 父列表属性更改后嵌套列表 UI 未更新 - Xamarin.Forms
- tensorflow - 在自定义 TF2.4 训练循环中应该如何使用指数移动平均线
- oauth-2.0 - Nextcloud 在 Moodle 的文件选择器中不可见
- macos - 将 HID 输入状态添加到 SwitfUI 环境
- android - 如何创建带有图标和文本的切换按钮