二叉树的前中后序查找

前序查找思路

1.先判断当前节点的no是否等于要查找的
2.如果相等,则返回当前的节点
3.如果不等,则判断当前节点的左子节点是否为空,如果不为空,则;递归前序查找
4.如果左递归前序查找,找到节点,则返回,否则继续判断,当前的节点的右子节点是否为空,如果不空,则继续向右递归前序查找

中序查找思路

1.判断当前节点的左子节点是否为空,如果不为空,则递归中序查找
2.如果找到。则返回,如果没找到,就和当前节点比较,如果是则返回当前节点,否则继续进行右递归的中序查找
3.如果右递归中序查找,找到就返回,否则返回null

后序查找思路

1.先判断当前节点的左子节点是否为空,如果不为空,则递归后序查找
2.如果找到,就返回,如果没找到,就判断当前节点的右子节点是否为空,不为空,就右递归进行后序查找,如果找到,就返回
3.就和当前节点进行,比如,如果是则返回,否则就返回null

首先写一个heroNode类里的查找方法
   /*前序查找*/
    public HeroNode preOrderSrearch(int no) {
        /*判断当前节点是不是*/
        if (this.id == no) {
            return this;
        }
        /*判断当前节点的左子节点是否为空,如果不为空,则递归前序查找
         * 如果左递归前序查找,找到节点,则返回*/
        HeroNode resNode = null;//定义一个接受结果的节点
        if (this.left != null) {
            resNode = this.left.preOrderSrearch(no);
        }
        if (resNode != null) {/*resNode有值说明找到了*/
            return resNode;/*直接返回接受查找*/
        }
        /*左子节点递归如果没有找到 ,则就进行右子节点递归查找*/
        if (this.right != null) {
            resNode = this.right.preOrderSrearch(no);
        }
        return resNode;
    }
/*中序查找*/
    public HeroNode midOrderSearch(int no) {
        HeroNode resNode = null;
        /*先进行左子节点递归查找*/
        if (this.left != null) {
            resNode = this.left.midOrderSearch(no);
        }
        if (resNode != null) {
            return resNode;
        }
        /*再进行判断*/
        if (this.id == no) {
            return this;
        }
        if (this.right != null) {
            resNode = this.right.midOrderSearch(no);
        }
        return resNode;
    }
/*后序查找*/
    public HeroNode endOrderSearch(int no) {
        HeroNode resNode = null;
        if (this.left != null) {
            resNode = this.left.endOrderSearch(no);
        }
        if (resNode != null) {
            return resNode;
        }
        if (this.right != null) {
            resNode = this.right.endOrderSearch(no);
        }

        return resNode;
    }
然后在binaryTree类中进行调用查找方法
   /*前序查找*/
    public HeroNode preOrderSearch(int no){
        if (root!=null){
          return   this.root.preOrderSrearch(no);
        }else{
            System.out.println("kong");
            return null;
        }
    }
/*中序查找*/
    public HeroNode midOrderSearch(int no){
        if(root!=null){
            return root.midOrderSearch(no);
        }
        return null;

    }
 /*后序查找*/
    public HeroNode endOrderSearch(int no){
        if (root!=null){
            return root.endOrderSearch(no);
        }
        return null;
    }
最后测试
/*查找测试*/
System.out.println("查找结果:");
HeroNode node = binaryTr.midOrderSearch(1);
System.out.println("node="+node);
这是结果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值