第十章 树

概述

二叉树概念

二叉树遍历(前中后序遍历)

思路 代码

public class BinaryTreeDemo {
    public static void main(String[] args) {
        //先需要创建一颗二叉树
        BinaryTree binaryTree = new BinaryTree();
        //创建需要的结点
        HeroPoint root = new HeroPoint(1, "宋江");
        HeroPoint node2 = new HeroPoint(2, "吴用");
        HeroPoint node3 = new HeroPoint(3, "卢俊义");
        HeroPoint node4 = new HeroPoint(4, "林冲");
        HeroPoint node5 = new HeroPoint(5, "关胜");

        //先手动创建该二叉树,后面递归的方式创建二叉树
        root.setLeft(node2);
        root.setRight(node3);
        node3.setRight(node4);
        node3.setLeft(node5);
        binaryTree.setRoot(root);

    	//测试
    	System.out.println("前序遍历"); // 1,2,3,5,4
    	binaryTree.perSortByRoot();
    	
    	System.out.println("中序遍历");
    	binaryTree.centerSortByRoot(); // 2,1,5,3,4
    	
    	System.out.println("后序遍历");
    	binaryTree.finalSortByRoot(); // 2,5,4,3,1
	
	}
}

class BinaryTree{
    private HeroPoint root;

    public void setRoot(HeroPoint root) {
        this.root = root;
    }

    public void perSortByRoot(){
        if (this.root != null){
            this.root.perSort();
        }else {
            System.out.println("前序遍历失败, 二叉树为空");
        }
    }

    public void centerSortByRoot(){
        if (this.root != null){
            this.root.centSort();
        }else {
            System.out.println("中序遍历失败, 二叉树为空");
        }
    }
    public void finalSortByRoot(){
        if (this.root != null){
            this.root.finalSort();
        }else {
            System.out.println("前序遍历失败, 二叉树为空");
        }
    }
}

class HeroPoint{

    private int id;
    private String name;

    private HeroPoint left;
    private HeroPoint right;


    public void perSort(){
        //输出
        System.out.println(this);

        //左遍历输出左节点
        if(this.left != null){
            this.left.perSort();
        }

        //右遍历输出右节点
        if(this.right != null){
            this.right.perSort();
        }
    }

    public void centSort(){
        //左遍历输出左节点
        if(this.left != null){
            this.left.centSort();
        }

        //输出序号
        System.out.println(this);

        //右遍历输出右节点
        if(this.right != null){
            this.right.centSort();
        }
    }

    public void finalSort(){
        //左遍历输出左节点
        if(this.left != null){
            this.left.finalSort();
        }
        //右遍历输出右节点
        if(this.right != null){
            this.right.finalSort();
        }

        //输出序号
        System.out.println(this);
    }

	get/set/toString方法

    public HeroPoint(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值