java - Java方法没有正确退出return语句
问题描述
我开始为二叉树编写一个函数。该方法目前旨在找到树中的节点并返回该节点。根值是数据,左右是子树。当我在调试器中单步执行它时,当它到达 return 语句时,它会跳回到第二个 if 块并最终返回 null。
@Override
public T successor(T d) {
T datas = null;
if (d.compareTo(this.data) < 0) //If its less than the root
left.successor(d);
if (d.compareTo(this.data) > 0) //If its less than the root
right.successor(d);
if (d.equals(this.data)){ //We found the node
datas = this.data;
}
return datas;
}
解决方案
您将忽略递归调用的返回值,并最终在调用堆栈中的特定点返回空值(数据)。
将您的代码更改为:
T datas = null;
if (d.compareTo(this.data) < 0) //If its less than the root
datas = left.successor(d);
if (d.compareTo(this.data) > 0) //If its less than the root
datas = right.successor(d);
if (d.equals(this.data)){ //We found the node
datas = this.data;
}
return datas;
或者,您可以删除局部变量并将其简化为
if (d.compareTo(this.data) < 0) {
return left.successor(d);
} else if (d.compareTo(this.data) > 0) {
return right.successor(d);
}
return this.data;
更新:这假设正在搜索的值存在。当左/右为空时,您必须小心。
推荐阅读
- eloquent - Laravel 多重下拉搜索
- python - 如果有人兑换积分,如何获取信息?
- python - 如何在多进程中更新 Tkinter 小部件?
- ios - React 应用程序未在 Capacitor iOS 模拟器中加载
- multithreading - tcl 多线程:在循环中多次调用函数的最佳方法
- workbench - Aginity 工作台自动缩进/SQL 格式化程序
- azure - Azure 应用注册和 Azure 服务主体使用
- c# - 如何通过 Gmail API 从 .net 核心控制台应用程序发送电子邮件?
- java - 如何在maven项目中添加talend jars依赖
- python - 通过代码调用pytest并将结果保存到变量或文件中