首页 > 解决方案 > 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;
}

标签: javatreebinary-search-tree

解决方案


您将忽略递归调用的返回值,并最终在调用堆栈中的特定点返回空值(数据)。

将您的代码更改为:

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;

更新:这假设正在搜索的值存在。当左/右为空时,您必须小心。


推荐阅读