我是递归的新手,我不明白为什么这个函数不能编译。它显然缺少返回语句。从测试来看,好像我的返回语句也没有返回?
// recursive search method
public BinaryTree<T> recursiveSearch(BinaryTree<T> t, T key) {
if (key.compareTo(t.getData()) < 0) {
if (t.getLeft() != null) {
recursiveSearch(t.getLeft(), key);
} else {
return null;
}
} else if (key.compareTo(t.getData()) > 0) {
if (t.getRight() != null) {
recursiveSearch(t.getRight(), key);
} else {
return null;
}
} else if (key.compareTo(t.getData()) == 0) { // key is found
return t;
} else { // not in binary tree
return null;
}
}
最佳答案
问题出在进行递归调用的 if
分支中。
当您的代码到达您的任何 else
分支时,它会正确运行,因为它们都具有 return null
。但是,如果代码采用 if
分支之一,控件将到达您的方法的末尾而不会点击 return
。修复很简单 - 添加缺少的 return
s:
return recursiveSearch(t.getRight(), key);
关于java - 递归函数缺少返回语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617257/