二叉树的前序、中序、后序遍历Java实现

首先创建二叉树类

/**
 * 
 * @author OucJeffrey
 * qq:1020724110
 * weibo:ouc大飞
 */
public class BinaryTree {
    int data;//根节点数据
    BinaryTree left;//左子树
    BinaryTree right;//右子树
    public BinaryTree(int data){//构造方法,实例化二叉树类
        this.data=data;
        left=null;
        right=null;
    }
    public void insert(BinaryTree root,int data){//向二叉树中插入子节点
        if (data>root.data) {//二叉树的右节点都比根大
            if (root.right==null) {
                root.right=new  BinaryTree(data);
            }else {
                this.insert(root.right, data);
            }
        }else {//二叉树的左节点都比根小
            if (root.left==null) {
                root.left=new  BinaryTree(data);
            }else {
                this.insert(root.left, data);
            }

        }

    }

}

接着就是二叉树的前中后遍历了


/**
 * @author OucJeffrey
 * qq:1020724110
 * weibo:ouc大飞
 */

public class BinaryTreeOrder {
    public static void main(String[] args) {
        int[] array={12,11,4,7,34,23,56,43,22,11,55};
        BinaryTree root=new  BinaryTree(array[0]);
        for(int i=1;i<array.length-1;i++){
            root.insert(root, array[i]);
        }
        System.out.println("先序遍历");
        preOrder(root);
        System.out.println();
        System.out.println("中序遍历");
        inOrder(root);
        System.out.println();
        System.out.println("后序遍历");
        postOrder(root);
    }
    public static void preOrder(BinaryTree root){//先序遍历
        if (root!=null) {
            System.out.print(root.data+"--");
            preOrder(root.left);
            preOrder(root.right);
        }
    }
    public static void inOrder(BinaryTree root){//中序遍历
        if(root!=null){
            inOrder(root.left);
            System.out.print(root.data+"--");
            inOrder(root.right);
        }
    }
    public static void postOrder(BinaryTree root){//后续遍历
        if (root!=null) {
            postOrder(root.left);
            postOrder(root.right);
            System.out.print(root.data+"--");
        }
    }

}

遍历结果

先序遍历
12--11--4--7--11--34--23--22--56--43--
中序遍历
4--7--11--11--12--22--23--34--43--56--
后序遍历
11--7--4--11--22--23--43--56--34--12--
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值