逻辑Bug:在使用递归时的返回问题

最近练习时写了个简单的二叉搜索树,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);
		}
	}
}
说到底还是对递归不熟练造成的!


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值