二叉树查找指定结点

二叉树查找指定结点

查找方式分为三种:

  • 前序查找
  • 中序查找
  • 后续查找

代码实现一下~

class HeroNode{
	// 1 前序查找 
    public HeroNode preOrderSearch(int no){
        System.out.println("前序查找");
        HeroNode temp = null; // 定义一个存储结点

        if (this.no == no){
            return this; // 比较当前结点,找到则返回
        }

        if (this.left != null){
            temp = this.left.preOrderSearch(no); // 向左递归
        }
        if (temp != null){
            return temp; // 左递归过程中如果不为null则返回查询的结果
        }

        if (this.right != null){
            temp = this.right.preOrderSearch(no); // 进行右递归
        }
        return temp;
    }
    
    // 2 中序查找
    public HeroNode infixOrderSearch(int no){

        HeroNode temp = null;
        if (this.left != null){
            temp = this.left.infixOrderSearch(no); // 向左递归
        }

        if (temp != null){
            return temp; // 向左递归时找到了
        }
        System.out.println("中序查找");
        if (this.no == no){
            return this; // 判断当前结点是否满足条件
        }

        if (this.right != null){
            temp = this.right.infixOrderSearch(no); // 如果右边还有则向右递归
        }
        return temp; // 返回结果
    }
    // 3 后续查找
    public HeroNode postOrderSearch(int no){

        HeroNode temp = null;
        if (this.left != null){
            temp = this.left.postOrderSearch(no); // 左递归
        }
        if (temp != null){
            return temp;
        }
        if (this.right != null){
            temp = this.right.postOrderSearch(no); // 右递归
        }
        if (temp != null){
            return temp; // 返回
        }
        System.out.println("后序查找");
        if (this.no == no){
            return this;
        }
        return temp;
    }
}

注意:

  1. 需要注意打印语句的位置,让它在判断语句之前出现,否则有些无效的递归也会输出它(有些递归仅仅是进入下一次递归,并没有进行与结点的比较)

  2. HashTable中调用HeroNode里面提供的方法!

// HashTable中提供的查找
// 前序查找
public HeroNode preOrderSearch(int no){
    if (root != null){
        return root.preOrderSearch(no);
    }else {
        return null;
    }
}
// 中序查找
public HeroNode infixOrderSearch(int no){
    if (root != null){
        return root.infixOrderSearch(no);
    }else {
        return null;
    }
}
// 中序查找
public HeroNode postOrderSearch(int no){
    if (root != null){
        return root.postOrderSearch(no);
    }else {
        return null;
    }
}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值