二叉树的查找(前序,中序,后序)

二叉树的查找

先要了解二叉树的构成和创建1个二叉树
链接: 二叉树的遍历(前序遍历,后序遍历,中序遍历)

前序查找

思路:
1.先判断当前节点的no值是否等于要查找的。
如果相等,则直接返回当前节点
2.如果不相等,则判断判断左子节点是否为null,如果不为null,则直接递归左子树。
3.如果左递归找到了,就直接返回,如果没有找到,就递归右子树。
代码:

//前序查找
    public HeroNode preOrderSearch(int no){
        //先比较当前的节点是不是
        if(this.no == no){
            //如果是 直接返回
            return this;
        }
        //否则递归左子树继续遍历
        HeroNode heroNode = null;
        if(this.left != null){
            heroNode = this.left.preOrderSearch(no);
        }
        //说明在左子树中找到了
        if(heroNode != null){
            return heroNode;
        }
        //在左子树中没找到,就继续去右子树找
        if(this.right != null){
            heroNode = this.right.preOrderSearch(no);
        }
        //如果都没有找到的话返回的就是null
        return heroNode;
    }

中序查找

思路:
1.判断当前节点的左子节点是否为null,如果不为null,则递归左子树。
2.如果找到,就直接返回,没有找到,就去和当前节点(root)的no进行比较,如果相等就返回当前的节点。否则递归右子树
3.在右子树中找到,就直接返回,没找到就返回null。
代码:

//中序查找
    public HeroNode infixSearch(int no){
        HeroNode heroNode = null;
        //先比较左子树中是否存在
        if(this.left != null){
            heroNode = this.left.infixSearch(no);
        }
        //找到就直接返回
        if(heroNode != null){
            return heroNode;
        }
        //接着判断当前节点
        if(this.no == no){
            return this;
        }
        //接着分析右子树
        if(this.right != null){
            heroNode = this.right.infixSearch(no);
        }
        //如果都没有找到的话返回的就是null
        return heroNode;
    }

后序查找

思路:
1.判断当前的左子节点是否为null,如果不为null,就递归左子树进行查找。
2.如果找到了,就直接返回。没有找到就判断右子节点是否为null,如果不为null,就直接递归右子树进行查找。
3.如果找到了,就直接返回,否则就去和当前节点(root)的no进行比较,如果相等就返回当前的节点。不相等就返回null。
代码:

//后序查找
    public HeroNode postSearch(int no){
        HeroNode heroNode = null;
        //先判断左子树是不存在该值
        if(this.left != null){
            heroNode = this.left.postSearch(no);
        }
        if(heroNode != null){
            return heroNode;
        }
        //再去看右子树
        if(this.right != null){
            heroNode = this.right.postSearch(no);
        }
        if(heroNode != null){
            return heroNode;
        }
        //最后去找根节点
        if(this.no == no){
            return this;
        }
        return heroNode;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲键盘的程序源

你的激励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值