最近练习时写了个简单的二叉搜索树,find方法采用递归,开始是这样写的:
public boolean find(int key) {
if(this.data == key) {
//System.out.println("true");
return true;
}
if(key < this.data && this.leftChild != null) {
leftChild.find(key);
} else if(this.rightChild != null){
rightChild.find(key);
}
return false;
}
在树中添加了三个元素50,25,75,发现find(25)返回的总是false。于是我在方法return true之前加了一句
System.out.println("true"); 发现可以显示,这说明return true执行了。断点进去执行发现,return true以后程序居然还在往下执行!一直执行到最后的return false,于是返回的都是false了。
研究了半天发现,这个return true其实是递归执行一次以后的程序的返回值,也就是说其实原来的方法还没有执行完,只是第一层的递归执行完了,而我却以为整个方法都执行完成了!
修改后的代码如下:
public boolean find(int key) {
if(this.data == key) {
return true;
}
if(key < this.data) {
if(this.leftChild == null) {
return false;
} else {
return leftChild.find(key);
}
} else {
if(rightChild == null){
return false;
} else {
return rightChild.find(key);
}
}
}
说到底还是对递归不熟练造成的!