Java实现二叉树的遍历

开局一张糊糊的图
在这里插入图片描述

  • 节点
public class TreeNode {
    public int val;//节点值
    public TreeNode left;//指向该节点的左孩子 null表示无左孩子 进一步视为左子树
    public TreeNode right;//指向该节点的右孩子

    public TreeNode(int val) {
        this.val = val;
    }
    @Override
    public String toString() {
        return String.format("TreeNode{%c}",val);
    }
}
  • 生成二叉树
public class BuildTree {
    public static TreeNode buildTree(){
        TreeNode a=new TreeNode('a');//所有节点
        TreeNode b=new TreeNode('b');
        TreeNode c=new TreeNode('c');
        TreeNode d=new TreeNode('d');
        TreeNode e=new TreeNode('e');
        TreeNode f=new TreeNode('f');
        TreeNode g=new TreeNode('g');
        TreeNode h=new TreeNode('h');

        a.left=b;a.right=c;
        b.left=d;b.right=e;
        c.left=f;c.right=g;
        e.right=h;

        return a;//返回根节点
    }
}

  • 前序、中序、后序遍历(用递归实现)
public class TreeTraversal {
    public static void main(String[] args) {
        TreeNode root=BuildTree.buildTree();

        System.out.print("前序遍历:");
        preorder(root);
        System.out.println();

        System.out.print("中序遍历:");
       inorder(root);
        System.out.println();

        System.out.print("后序遍历:");
        postorder(root);
        System.out.println();
    }
    public static void preorder(TreeNode root) {//前序遍历
        if (root == null){
            return;
        }
        //遍历任意节点 只需打印根的值
        System.out.printf("%c ",root.val);
        //递归
        preorder(root.left);//root.left代表一整棵左子树
        preorder(root.right);
    }

    public static void inorder(TreeNode root){//中序遍历
        if (root==null){
            return;
        }
        inorder(root.left);
        System.out.printf("%c ",root.val);
        inorder(root.right);
    }
    public static void postorder(TreeNode root){
        if (root==null){
            return;
        }
        postorder(root.left);
        postorder(root.right);
        System.out.printf("%c ",root.val);
    }
}

  • 执行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值