数据结构之树的遍历

JAVA实现树的遍历

注:主要是指二叉树 D是指根节点,L是左节点,R是右节点
在这里插入图片描述

前序遍历

DRL (先取根节点,再取左节点,最后取右节点)

结果:
1-2-4-5-3-6-7

public void frontShow(){
    System.out.print(this.getValue()+"\t");
    if(this.treeLeftNode!=null){
        this.treeLeftNode.frontShow();
    }
    if(this.treeRightNode!=null){
        this.treeRightNode.frontShow();
    }
}
中序遍历

LDR(先取左节点,再取根点,最后取右节点)
结果:
在这里插入图片描述

public void midShow(){
    if(this.treeLeftNode!=null){
        this.treeLeftNode.midShow();
    }
    System.out.print(this.getValue()+"\t");
    if(this.treeRightNode!=null){
        this.treeRightNode.midShow();
    }
}
后序遍历

LRD(先取左节点,再取右节点,最后取根节点)

结果:
在这里插入图片描述

public void finalShow() {
    if (this.treeLeftNode != null) {
        this.treeLeftNode.finalShow();
    }
    if (this.treeRightNode != null) {
        this.treeRightNode.finalShow();
    }
    System.out.print(this.getValue() + "\t");
}

注:每到一个新的节点,就要用遍历的思想进行判断取哪个节点,这可以用递归的思想处理

使用遍历的思想实现树节点的查找

前序查找
public TreeNode frontSearch(int i) {
    TreeNode target = null;
    if (i == this.getValue()) {
        return this;
    } else {
        //查询左节点
        if (this.treeLeftNode != null) {
            target = treeLeftNode.frontSearch(i);
        }
        //如果左节点找到了就不用遍历右节点
        if (target != null) {
            return target;
        }
        //查询右节点
        if (this.treeRightNode != null) {
            target = treeRightNode.frontSearch(i);
        }
    }
    return target;
}
中序查找

//中序查找

public TreeNode midSearch(int i) {
    TreeNode target = null;
    if (this.treeLeftNode != null) {
        target = this.treeLeftNode.midSearch(i);
    }
    if (target != null) {
        return target;
    }
    if (this.getValue() == i) {
        return this;
    } else {
        if (this.treeRightNode != null) {
            target = this.treeRightNode.midSearch(i);
        }
        return target;
    }
}
后序查找
//后续查找
public TreeNode afterSearch(int i){
    TreeNode target = null;
    if(this.treeLeftNode!=null){
       target = this.treeLeftNode.afterSearch(i);
    }
    if(target!=null){
        return target;
    }
    if(this.treeRightNode!=null){
        target = this.treeRightNode.afterSearch(i);
    }
    if(this.getValue()==i){
        return this;
    }
    return target;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值